How to solve the “Warning: Can’t perform a React state update on an unmounted component.” when using React Hooks

Situation

You are having a React Component using Hooks. In that component, you use useEffect to perform some asynchronous actions and update the component state.

const [count, increase] = useState(0);
useEffect(() => {
  //count will increase after 3 secs
  setTimeOut(() => increase(count++), 3000);  
});

Problem

When you run the app and there is a warning shown in console:

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

This happens because your component is unmounted but the asynchronous action doesn’t complete (the setTimeOut have to wait 3 secs then update the state but the component was unmounted).

This maybe leaks the memory and affects the performance of the app.

Solution

You can set a flag to check if the component is unmounted.

useEffect(() => {
  let didUnmount = false;
  setTimeOut(() => {
    if (!didUnmout) {
      increase(count++);
    }
  }, 3000);

  //The cleanup will be called when the component is unmounted 
  return () => { 
    didUnmount = true; 
  };
});

Hope this helps!

Bình luận về bài viết này

Tạo một blog trên WordPress.com

Lên ↑

Tạo trang giống vầy với WordPress.com
Hãy bắt đầu