Memory leak

React memory leaks

Alexander Luria
1 min readOct 14, 2021

--

You are in charge of writing a component that updates something periodically, sleep, and then check if it has to update something again.

Problem:

Once the flag to update becomes negative, but you have the component still mounted, useEffect still holds the last update timer open and will trigger the update even when it has no permission to do so.

Result:

Memory leak in form of updating unmounted component and the browsers is not happy.

Solution:

When setting interval or timeout clear functions make sure you:
A: Trigger the interval only when the update flag is positive.
B: Store the cancel function or the interval ID available to the local component scope.

Reasons:

When triggering a new setInterval you will get a new interval id. When the update is cancelled you will still hold the old ID and will try to cancel the new ID. That is why you must store the ID outside the useEffect, to effectively cancel the correct timeout trigger and not the stale one.

--

--

Alexander Luria

Veteran Front end developer. Obsessing over ROI development. Addicted to online FPS.