Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React setTimeout - memory leak

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> 
        
        );
    };
like image 274
upog Avatar asked Sep 01 '25 20:09

upog


1 Answers

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

like image 54
raina77ow Avatar answered Sep 05 '25 02:09

raina77ow