Posts

Showing posts with the label Setstate

Can't Perform A React State Update On An Unmounted Component

Answer : 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 this flag denote mount status someAsyncOperation().then(data => { if (isMounted) setState(data); }) return () => { isMounted = false }; // use effect cleanup to set flag false, if unmounted }); const Parent = () => { const [mounted, setMounted] = useState(true); return ( <div> Parent: <button onClick={() => setMounted(!mounted)}> {mounted ? "Unmount" : "Mount"} Child </button> {mounted && <Child />} <p> Unmount Child, while it is still ...