I have the below component , where i am displaying message for 5 sec and then removing it from home page.
when i switch between the pages, i'm getting below error sometimes. Any Advice please
index.js:1 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.
Code:
const Home = props => {
const [visible, setVisible] = useState(true);
useEffect(() => {
setTimeout(() => setVisible(false), 5000);
}, []);
return (
<div >
{visible && <Message showDefault={false} /> }
<BaseView />
</div>
);
};
Well, the error is actually quite self-explanatory: the state-changing function triggered by setTimeout
is invoked after the component has already been unmounted. But it's no-op in disguise: component is no longer rendered, why should anyone be interested in its internal state changes?
Thankfully, React provides a documented way to clean up those and similar async state-changers - by using a function returned by an useEffect
callback. Like this:
useEffect(() => {
const timeoutId = setTimeout(() => setVisible(false), 5000);
return function cleanup() {
clearTimeout(timeoutId);
}
}, []);
Note that the function doesn't have to be named (but it simplifies reading a bit).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With