Wanna see something cool? Check out Angular Spotify 🎧
All Articles

Warning: Can’t perform a React state update on an unmounted component

If you are a react developer, there is a good chance that you faced this warning at least once:

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

I got this issue as well and recently, I found an excellent blog post that explains why it happens and how to fix it. In short, it is happening when you are updating a component state after a task that takes time to complete. By the time it finishes, you have already shown another component.

You can see how it is reproduced below.

And this is the full blog post from Sagiv Ben Giat.

The proper and reusable fix is introducing a new hook named useIsMountedRef to check before you update your component state.

function useIsMountedRef() {
  const isMountedRef = useRef(null)
  useEffect(() => {
    isMountedRef.current = true
    return () => (isMountedRef.current = false)
  })
  return isMountedRef
}
Published 15 May 2021

Recent Posts

Angular Singapore

Follow @angularsg for the upcoming events :)

Angular - Set page title automatically!

Using a few lines of code could make the application feel much better!


Follow @tuantrungvo on Twitter for more!