What Happens if You Try to Set the State of an Unmounted Component??

Have you ever seen the error, “Can’t perform a React state update on an unmounted component” in your application? Unsure why it’s happening or how to prevent it?

Let’s explore with an example.

const Timer = ({ time, callback }) => {
const [timeLeft, setTimeLeft] = useState(time);

useEffect(() => {
const interval = setInterval(() => {
setTimeLeft((prevTime) => prevTime - 1);
if (timeLeft === 0) {
callback();
}
}, 1000);
}, [time]);

return <div>{timeLeft}</div>;
};

export default Timer;

Scenario Explained

When the time prop changes, React will unmount this component and replace it with a new instance. However, if the interval isn't cleared, it will continue running, trying to update the state of an unmounted component. This can lead to the warning: "Can't perform a React state update on an unmounted component."

Potential Issues

  1. Memory Leak: If the interval keeps running even after the component unmounts, it holds onto memory unnecessarily. If many such intervals accumulate, it can lead to memory leaks, potentially causing the app to crash.
  2. Unexpected Behaviour: The interval might try to update the component’s state, causing unpredictable behaviour. For instance, if it references outdated props or state, it could trigger stale updates.

Solution: Clear the Interval on Unmount

To prevent this, we can clear the interval when the component unmounts. Here’s how to fix the useEffect:

useEffect(() => {
const interval = setInterval(() => {
setTimeLeft((prevTime) => prevTime - 1);
if (timeLeft === 0) {
callback();
}
}, 1000);

// Cleanup function to clear the interval on component unmount
return () => {
clearInterval(interval);
};
}, [time]);

By adding a cleanup function with return () => clearInterval(interval);, we ensure that the interval stops when the component unmounts, avoiding unnecessary state updates on unmounted components.

General Advice

This is just one example of many potential scenarios where state updates on unmounted components may occur. For such issues, inspect your code to identify areas where previous state or props might be accessed incorrectly and update the logic accordingly.

Queries and Doubts

Thanks for the read :) Hope you have enjoyed reading it 🤩 and learnt something new today.

If you have any doubts or queries feel free to drop a comment or

⁍ Connect with me on my 🔗Topmate 💬.

⁍ You can also reach out to me on my 🔗LinkedIn.

⁍ Please clap for this post if you enjoyed reading it 📗 and follow for more interesting articles.

⁍ You can also support me and my writings by treating me to a nice virtual cup of coffee ☕️.

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go: