Wanna see something cool? Check out Angular Spotify 🎧

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

Read more

 — Angular - Set page title automatically!
 — Angular Singapore
 — A simple Spotify client built with Angular 11, Nx workspace, ngrx, TailwindCSS and ng-zorro
 — Nx Workspace structure for an application with NestJS and Angular
 — SVG fill color doesn't work with hex colors