Can't perform a React state update on an unmounted component Can't perform a React state update on an unmounted component javascript javascript

Can't perform a React state update on an unmounted component


Here is a React Hooks specific solution for

Error

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

Solution

You can declare let isMounted = true inside useEffect, which will be changed in the cleanup callback, as soon as the component is unmounted. Before state updates, you now check this variable conditionally:

useEffect(() => {  let isMounted = true;               // note mutable flag  someAsyncOperation().then(data => {    if (isMounted) setState(data);    // add conditional check  })  return () => { isMounted = false }; // cleanup toggles value, if unmounted}, []);                               // adjust dependencies to your needs