Answer the question
In order to leave comments, you need to log in
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>
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question