Stop Memory Leaks with componentWillUnmount Lifecycle Method in React

Kent C. Dodds
InstructorKent C. Dodds

Share this video with your friends

Send Tweet

In this lesson, we have a stopwatch component that will update the time since it was run in milliseconds. The problem is, if you unmount the component, there is a memory leak because the interval that is set when you start and the timer is not stopped. React provides the componentWillUnmount lifecycle method as an opportunity to clear anything that needs to be cleared when the component is unmounted or removed from the DOM.

Jose
Jose
~ 4 years ago

This is a brilliant bug to point out and fix. I certainly wouldn't have caught it unless I had the console open. What other sorts of memory leaks do we need to keep an eye out for, aside from circular references, clear intervals, and clear timeouts?

Kent C. Dodds
Kent C. Doddsinstructor
~ 4 years ago

Thanks Jose. There's also subscriptions. A bunch of different things that will leave instance functions referenced by something else. Good luck!

Efe Mumoglu
Efe Mumoglu
~ 2 years ago

Hi, Excellent course! To improve this class, it would be great if you shortly mention that 'state' is a predefined object of the Component and setState is a method of the Component that updates state object and triggers render for the component (just like the one setState function we wrote in the previous class). Sometimes it gets vague what is a framework variable name, and what is custom variable.

David Dean
David Dean
~ 2 years ago

There is so much packed in this relatively compact course. It's great that you still make time for this real life issue.

Ankur Jain
Ankur Jain
~ 2 years ago

Hi, just wanted to understand why do we need arrow function for event handlers, when i am using normal class functions, i am getting 'this' as undefined. It would be great if i can have some light on this. Thanks!

Ankur Jain
Ankur Jain
~ 2 years ago

Hi, Got the answer in the next Lesson. Thanks Kent for the great course!