React hooks - right way to clear timeouts and intervals

后端 未结 6 808
感情败类
感情败类 2020-12-01 02:54

I don\'t understand why is when I use setTimeout function my react component start to infinite console.log. Everything is working, but PC start to lag as hell.

6条回答
  •  天命终不由人
    2020-12-01 03:02

    Your computer was lagging because you probably forgot to pass in the empty array as the second argument of useEffect and was triggering a setState within the callback. That causes an infinite loop because useEffect is triggered on renders.

    Here's a working way to set a timer on mount and clearing it on unmount:

    function App() {
      React.useEffect(() => {
        const timer = window.setInterval(() => {
          console.log('1 second has passed');
        }, 1000);
        return () => { // Return callback to run on unmount.
          window.clearInterval(timer);
        };
      }, []); // Pass in empty array to run useEffect only on mount.
    
      return (
        
    Timer Example
    ); } ReactDOM.render(
    , document.querySelector("#app") );
    
    
    
    

提交回复
热议问题