I came accross this code
const [count, setCount] = useState(0);
useEffect(() => {
const timerId = setTimeout(() => setCount(count + 1), 1000);
return () => setTimeout(timerId);
});
I know useEffect syntax as
useEffect(() => {
something...which is executed
});
but in the code i see its returning inside useEffect
useEffect(() => {
....
return () =>
});
As per my understanding how its different from just
useEffect(() => {
//const timerId = setTimeout(() => setCount(count + 1), 1000);
setTimeout(() => setCount(count + 1), 1000);
//return () => setTimeout(timerId);
});
i am bit confused how this works
2
Answers
As pointed out in the answer here the return of the
useEffect
is to clean up and, the returned function is run when the component is unmounted or every time it is rendered.So to answer how is
different from
I think it is the confusion on the part of the Author of the first snippet. I think the intended code was
Since the timeout is bound to the
window
(global scope), the author meant to clear the previous timeout on each render or when the component is unmounted.If you return function inside useEffect, it’s called
cleanup function
This function is executed when the component is unmounted.What the author was trying to do is that clear the timer when the component is unmounted but, I think the code you came across kinda confusing anyway
I think it should be like this..