Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Stop Memory Leaks with componentWillUnmount Lifecycle Method in React

    Kent C. DoddsKent C. Dodds

    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.

    reactReact
    ^16.0.0
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 There's actually a pretty serious bug in this implementation, and I added this checkbox to show and hide our stopwatch so that we can reveal this bug. When I uncheck it, it actually removes the component from the dom. When I check it again, it'll re-add it and create a brand-new instance and re-render that.

    00:17 If I go ahead and add a callback here inside of set state call and I console log this.state.laps, and then we pop open our developer console and I hit start, I'm going to see this number being incremented a millions times logged to the console.

    00:35 Then if I click on show stopwatch to un-show it, we're actually going to get this warning. It actually isn't doing anything wrong in our application, but it is indicative of a memory leak. That's exactly what's happening here.

    00:48 We need to fix this memory leak. The problem is that the set interval is never cleared, so we need to go ahead and clear that. Let's go ahead and do that with component will unmount. Right before React removes the component from the page, it's going to call this function.

    01:03 We'll simply say clear interval this.timer. Now, we can start, and then remove the stopwatch, and it's totally gone. We don't see the logs anymore and we don't get that warning.

    Discuss

    Discuss