close

[Solved] Can’t perform a React state update on an unmounted component in React-hooks.

Hello Guys, How are you all? Hope You all Are Fine. Today I am facing data is started and component was unmounted but I am facing following error Can’t perform a React state update on an unmounted component in React-hooks in reactjs. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Can’t perform a React state update on an unmounted component in React-hooks Error Occurs ?

Today when fetching of data is started and the component was unmounted, but the function is trying to update the state of the unmounted component. But I get this error:

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.

How To Solve Can’t perform a React state update on an unmounted component in React-hooks Error ?

  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. For Example.

  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. For Example.

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!

Just install use-state-if-mounted by this command

npm install use-state-if-mounted

Here is how you can use

const [count, setCount] = useStateIfMounted(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>;
}

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?

Also Read

2 thoughts on “[Solved] Can’t perform a React state update on an unmounted component in React-hooks.”

  1. Awesome,
    Been at it for 3 hrs
    Coincidently, I am creating a website similar to Net-a-porter on Client’s request 🙂

    Reply

Leave a Comment