Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

clearTimeout() not working properly inside useEffect

I have the following useEffect:


useEffect(() => {
    const closeFeedbackTimer = setTimeout(() => {
      console.log('test')
    }, 5000)

    if (!finishedFeedbackOpen) {
      clearTimeout(closeFeedbackTimer)
    }
  }, [finishedFeedbackOpen])

And finishedFeedbackOpen is set to true/false with a function inside my component.

The problem is: when finishedFeedbackOpen is set to false, the timeout is not cleared, even if entering the if condition.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you should use the return function to clearTimeout inside useEffect. modify your code to something below

useEffect(() => {
    
    if (finishedFeedbackOpen) {
      const closeFeedbackTimer = setTimeout(() => {
         console.log('test')
       }, 5000)

      return ()=> clearTimeout(closeFeedbackTimer)
    }
  }, [finishedFeedbackOpen])

More info on it here: https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading