DEV Community

Cover image for Solve: can’t perform a react state update on an unmounted component
Reactjs Guru
Reactjs Guru

Posted on

Solve: can’t perform a react state update on an unmounted component

In React, components are responsible for rendering different parts of your user interface. They can have their own state, which is a JavaScript object that holds data specific to that component. The state allows components to manage and update their data, resulting in dynamic and interactive user interfaces.

However, there are situations where a component may be removed or unmounted from the DOM. This can happen for various reasons, such as when a component is hidden, removed from the screen, or when the parent component is updated and causes the child component to be unmounted.

Now, let’s consider a scenario where you have a component that performs an asynchronous operation, like fetching data from an API. This asynchronous operation may take some time to complete. While the operation is in progress, the component is still mounted and part of the DOM.

However, if the component gets unmounted before the asynchronous operation finishes, it means that the component is no longer present in the DOM. At this point, if you try to update the state of that unmounted component, React will throw the error message “Can’t Perform a React State Update on an Unmounted Component.”

The reason for this error is that React is trying to prevent you from updating the state of a component that no longer exists in the DOM. Since the component is unmounted, there is no associated user interface element to update, and modifying the state would be meaningless.
Read More with Example Here

Top comments (1)

Collapse
 
brense profile image
Rense Bakker

This error also serves as reminder that you forgot to clean up a side effect, like a fetch or event listener. It happens often when people forget to return a cleanup function when they use the useEffect hook:

function ComponentWithSideEffect() {
  const onResize = useCallback(() => {
    // ... Do stuff
  }, [])
  useEffect(() => {
    addEventListener('resize', onResize)
    // Must return a cleanup function for the side effect!
    return () => removeEventListener('resize', onResize)
  }, [])
  return // ... Render component
}
Enter fullscreen mode Exit fullscreen mode