02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School

Events as main cause of Memory Leaks

Understanding Immutability in JavaScript

Immutability is a foundational concept in modern JavaScript development, aiming to prevent unintended changes to data and optimize application performance. This tutorial introduces immutability, its advantages, and how to use the Immutable.js library.


What is Immutability?

Immutability means creating data structures that cannot be altered after they are created. Any modification results in a new data structure. This principle simplifies debugging, enhances performance, and ensures predictable behavior.


Key Benefits of Immutability:

  1. Simplified Debugging: Immutable objects ensure data integrity by preventing unintended changes.
  2. Memory Efficiency: Only new changes are stored, leveraging existing references.
  3. Improved Performance: Immutable objects reduce computational overhead during state updates.
  4. Error Prevention: Attempts to alter immutable data raise errors, encouraging better coding practices.

Implementing Immutability with Immutable.js

The Immutable.js library by Facebook provides efficient, immutable data structures such as Maps, Lists, and Sets.


Basic Usage
  1. Installation:
    npm install immutable
    
  2. Creating Immutable Maps:
    import { Map } from 'immutable';
    
    const initialMap = Map({ a: 1, b: 2 });
    const updatedMap = initialMap.set('b', 3);
    
    console.log(initialMap === updatedMap); // false
    console.log(initialMap.get('b')); // 2
    console.log(updatedMap.get('b')); // 3
    
  3. Immutability in Action: Changes create new structures without altering the original.

Advanced Features
  • Efficient Updates: Only changed values are updated, while other references remain intact.
  • Memory Optimization: Immutable.js uses structural sharing to minimize memory use.

Best Practices

  1. Use Constants: Define values that do not change.
  2. Avoid Mutable Operations: Refrain from modifying arrays or objects directly.
  3. Leverage Immutable.js: Utilize library features for complex data handling.

When to Use Immutability

  • State Management: Frameworks like Redux benefit greatly from immutable state structures.
  • High-Frequency Updates: Applications with frequent data changes can optimize rendering and memory use.

Final Thoughts

Immutability is essential for creating robust, scalable JavaScript applications. With tools like Immutable.js, developers can write efficient, predictable code that performs well under complex scenarios.

Explore more techniques in this course: https://02geek.com/category/react/performance.

2024

As of 2024, immutability remains a fundamental principle in JavaScript development, particularly for enhancing code reliability, maintainability, and facilitating functional programming paradigms. However, the tools and approaches to achieve immutability have evolved.

Immutable.js in 2024

Immutable.js has been a prominent library for managing immutable data structures in JavaScript. It offers a suite of persistent data structures like Maps, Lists, and Sets, which are optimized for immutability and can minimize unnecessary copying. Despite its robust feature set, developers have noted that integrating Immutable.js can introduce complexity, especially when interoperating with native JavaScript objects and arrays. Additionally, the library's size and the learning curve associated with its API have led some teams to explore alternative solutions.

Emerging Alternatives

In recent years, several alternatives to Immutable.js have gained traction:

  • Immer: Immer allows developers to work with immutable data structures using a more natural and less intrusive syntax. It leverages JavaScript's native structures and provides a straightforward API for immutability, making it easier to adopt without significant changes to existing codebases.

  • Native JavaScript Enhancements: The ECMAScript 2024 (ES2024) specification introduces native support for immutable data structures through Records and Tuples. These additions enable developers to create deeply immutable data structures without relying on external libraries, simplifying the development process and reducing dependencies.

Conclusion

While Immutable.js continues to be a viable option for managing immutable data in JavaScript, the landscape in 2024 offers more streamlined and efficient alternatives. Libraries like Immer provide a less intrusive approach to immutability, and the native support introduced in ES2024 with Records and Tuples offers a compelling, dependency-free solution. Developers are encouraged to assess their specific project requirements and consider these modern alternatives to determine the most suitable approach for implementing immutability in their applications.

Video Transcript

00:01Generally speaking, when we're talking about memory leaks,
00:04the pro, the, the cause of it usually, if not always is
00:09an event or a timer, an event that you forgot to kill
00:13or an event that is a lot of events that are happening
00:15that you don't notice that you're continuously growing the
00:17amount of events or a lot of timers
00:20that are going on without you actually managing them.
00:23So we're gonna take a look at first of all how we should,
00:25how important it is for you to just reduce the amount
00:28of intervals and events that you use.
00:29Period React is really good at it
00:32because most things could be done without using events,
00:35but in the case that you do use an event you have
00:37to remember or a timer for that matter, you have
00:40to remember to always kill it.
00:41If you don't, that is the biggest performance killer
00:44and the biggest performance hog you could ever do
00:46to any JavaScript application.
00:48With that said, we're gonna take a look at how do we do
00:50that in a React application by using the component did mount
00:54and component will unmount methods
00:57that exist in the E ES six React library for its components.
01:04So our last overall JavaScript performance tip really goes
01:08back into React as well.
01:09And we're talking about events,
01:10but generally speaking in React most
01:13of the time we really don't need
01:14to worry too much about events.
01:16And that is because when we're actually working with them,
01:19we're usually not using events, we're using callbacks,
01:22we're sending properties,
01:23and when these elements will be deleted, then react,
01:26we'll deal with these events
01:27and delete them 'cause they're not events for us.
01:29For us, these are simple callbacks that are sent
01:31to our HTML.
01:33So we don't have to usually worry about events in React
01:35as long as we're working with this module.
01:38But what happens in situations
01:39where you just need an event for some reason?
01:42For example, I'm gonna take something that is derived out
01:44of the documentation of React
01:46and the link will be provided as well.
01:48What happens in this situation, for example, that we want
01:51to do something when our screen resizes Now to do that,
01:54this is not something built in.
01:55What I wanna do is I want to go ahead
01:57and reference to the, to the window itself and,
02:00and add an event listener.
02:02Now I'm not just gonna add it in directly anywhere.
02:04What I'm gonna do is I'm gonna create a callback,
02:06but I can't, but I can't reference directly
02:09to the window at any paint, not in a construct
02:12or anywhere else because I can't really reference it
02:14until the item is actually on the screen.
02:17So to be able to do that, I'm gonna call a callback
02:19that is built into React.
02:21That is called Component did Mount.
02:24Now the component did mount would be called once it's
02:26mounted and it's on the screen.
02:28Once it's on the screen,
02:29then now I have access to the window.
02:31So I could call the window add event list center
02:34and call in the event resize.
02:37'cause I wanna know whenever something is resized,
02:38in this case I'm gonna call the on resize.
02:41And as always, I'm gonna also make sure
02:43that my resize is also bound to the same.
02:46This. So I don't get any confusion between my, uh, roles
02:50of my, uh, this inside of my application.
02:53So I'm gonna bind it to this, making sure
02:55that anytime onary size is actually called it will still
02:58Maintain. Its,
02:59it's, it's, it's uh, uh, owner, it's this, it's
03:03who it is and onary size.
03:05I'm gonna go ahead and lemme just put here an event,
03:07not extends, just an event.
03:09And I'm gonna go ahead here and do a console log
03:14for our E And if I go ahead
03:16and run my application, if I don't have any errors,
03:19which hopefully I don't, but here we go.
03:20We have a small error. So this on resize, which is a no-no
03:24of course 'cause this, I don't need this.
03:26The way I define a ra, uh, functions inside of the new way
03:29of doing stuff with E ES six is literally just writing
03:31the name of the function.
03:32No need to even use the word function or,
03:34or the, the, the need of this either
03:37unless we're inside the construct already.
03:39Okay, so let's go ahead and just
03:40check if we don't have errors.
03:42And if we don't have errors,
03:43then everything is running, which everything is.
03:45If I go ahead here and I try to resize my screen here just
03:48for a second, every time I'm resizing it,
03:51we're gonna get access to our event itself,
03:53which is exactly what we wanna do.
03:56So in this case, we might wanna do something specific
03:58and my, I'm not gonna continue down the sample route
04:01'cause this part is already, you could figure out
04:03it's not part of performance.
04:05But now we could talk about performance issues.
04:07If at some point I'm gonna get rid of my app,
04:09I'm gonna create a memory leak because I have here an event
04:12and this event needs to be removed.
04:14And this is really critical
04:15because when I'm removing my item, this event,
04:18the reference, the window still exists.
04:20Thus the reference to this component will still exist.
04:22Even if we remove it or delete it, it really won't matter
04:25'cause we still have a reference living inside
04:27of this event, listener of the window.
04:29So to be able to deal with that,
04:31this is the big portion about memory leaks
04:34and one of the biggest reasons
04:35for memory leaks in applications.
04:37You wanna make sure also in any React application
04:40or for that matter, any JavaScript that you're creating,
04:43you'll also remove the event whenever it's applicable.
04:46So in this case, I want to call the component Will
04:51Unmount, which will basically be called just
04:54before we're removing it from the screen.
04:56So window is still there and I could go ahead
04:58and just say that, Hey, by the way, I wanna, this time
05:01around, I wanna remove my event, making sure
05:04that I'm gonna keep our memory leaks at bay.
05:08And this is really the biggest place
05:09where memory leaks could happen in React.
05:11And generally speaking, because we're not working
05:13with events and React is dealing with all these stuff
05:16behind the hood, usually, then usually we won't really have
05:18to worry too much about memory leaks.
05:20But clearly in these type of situations we would Now,
05:23generally speaking, anytime you're using an event, try
05:26to use them very minimalistically
05:28and also make sure that anytime you add an event,
05:30make sure you know where you're removing it
05:32and it actually will be removed when it needs to be removed.
05:35So with that said, that is really our topic about events.
05:38Now I have a lot more to talk about events,
05:40which I explore deeply in native JavaScript.
05:43So if you wanna check out my JavaScript high performance
05:46title and the platform that you're in, just search
05:48for JavaScript High Performance Ben Fowler.
05:50You'll find a whole title dedicated
05:53for pure JavaScript performance tips. With that said,
05:57We are done with overall JavaScript performance tips
06:00for this title because for the rest of the title
06:02and the rest of the sections,
06:03we're gonna be more explicitly react more explicitly
06:06creating the files, getting them ready for production.
06:11In this lecture we saw how to ma manage our memory
06:14by making sure that when we create events
06:16and react, we also remove them.
06:17And that is true also for any time
06:19where we might create or use.
06:22And that wraps up this section.
06:24In the next section, we're gonna start up a completely new
06:27topic, which will be about
06:28how do we render things on the server for our case?
06:30How do we server side render react applications
06:33to create isomorphic JavaScript
06:35or universal JavaScript to improve performance of your users
06:39by caching in the default first view
06:42that they see when their application first loads.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!