J
J
J. Snow2020-05-09 20:53:55
React
J. Snow, 2020-05-09 20:53:55

How to clear the timer when the component is dismantled?

Hi all!

I have a component written using React Hooks .
When you click on it, it starts a timer.
I want to stop this timer when the component is dismantled. I use useEffect
for this . The code is something like this:

function MyComponent() {
  const [timer, setTimer] = useState()
  
  useEffect(() => {
    return () => clearTimeout(timer) // timer всегда undefined
  }, [])
  
  return <a onClick={() => {
    setTimer(setTimeout(() => alert("Hi"), 5000))
  }}>Link</a>
}


Of course, the code doesn't work, because the function returned from useEffect has timer , which is undefined .

Question:
How to stop the timer when the component is dismantled?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-05-09
@j-snow

useEffect(() => () => clearTimeout(timer), [ timer ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question