Home > Enterprise >  clearTimeout() not working properly inside useEffect
clearTimeout() not working properly inside useEffect

Time:09-22

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.

CodePudding user response:

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

  • Related