React – cleanup, when and how?

When using features in React sometimes we need to understand the concept of cleanup.

Let’s look at an example using useEffect and useState. A useEffect and component state will only exist for the lifecycle of the component, which means when a component is unmounted it will be removed from memory. There is a nice way in React that allows us to perform some logic when this happens.

Why would we ever need to do this and how? Let’s consider this scenario:

This component has some local state that tracks the current page location. We update that by giving our global history module a callback that can update the state. All good? Well it will work… but it will leave a big mess when this component is unmounted and we change page.

Why is this…history is global and does not exist in memory because of this component, it will always be in memory, so even when this component is unmounted history will still live and it will still have what it thinks is a reference to the function setCurrentLocation. That of course is a problem because if the component is unmounted then that local state and its setter no longer exists, so when we change page now and it tries to invoke that callback…splat.

How can we fix this?…. cleanup!

So why does this work? The history module that is being used here returns a function from its listen method that can be used to unlisten. By storing that in a variable we now have a reference to it, that reference can be passed to the return of the useEffect to then be called when the component is unmounted, that means no more listening after our component is out of memory!