Search code examples
react-nativereact-hooksuse-effect

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


ERROR 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.


Solution

  • 1: How To Solve Can't perform a React state update on an unmounted component in React-hooks Error? To Solve Can't perform a React state update on an unmounted component in React-hooks Error Here is The easiest solution is to use a local variable that keeps track of whether the component is mounted or not.

    2: Can't perform a React state update on an unmounted component in React-hooks To Solve Can't perform a React state update on an unmounted component in React-hooks Error Here is The easiest solution is to use a local variable that keeps track of whether the component is mounted or not.

    SOLUTION 1: I built this hook that works just like React’s useState, but will only setState if the component is mounted. I find it more elegant because you don’t have to mess around with an isMounted variable in your component!

    const [count, setCount] = useState(0);

    SOLUTION 2 Here is The easiest solution is to use a local variable that keeps track of whether the component is mounted or not. For Example.

    function Example() {
      const [text, setText] = React.useState("waiting...");
    
      React.useEffect(() => {
        let isCancelled = false;
    
        simulateSlowNetworkRequest().then(() => {
          if (!isCancelled) {
            setText("done!");
          }
        });
    
        return () => {
          isCancelled = true;
        };
      }, []);
    
      return <h2>{text}</h2>;
    }