Invest with Cake DeFi and get guaranteed returns from your crypto assets. Register Now
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

Nx Workspace structure for an application with NestJS and Angular

This structure has been serving us really really well by enforcing consistency, promoting SCAM, prevent circular dependencies, and minimize mental overhead of "where to put what"

A simple Spotify client built with Angular 11, Nx workspace, ngrx, TailwindCSS and ng-zorro

An example of real-world monorepo codebase using Nx Workspace


Follow @tuantrungvo on Twitter for more!