Reputation: 495
I have the problem that the interval I am using in useEffect
isn't stopping when leaving the component.
The code is:
useEffect(() => {
const timer = window.setInterval(() => {
refreshSave();
}, 3000);
return () => {
window.clearInterval(timer);
};
}, []);
I am thinking about animating an empty span
and then using onAnimationIteration
to trigger the save.
Upvotes: 4
Views: 2154
Reputation: 10655
I faced a similar issue before, solved it by using the useRef
hook.
const funRef = useRef(null);
//...
useEffect(() => {
funRef.current = setInterval(() => {
refreshSave();
}, 3000);
return () => {
clearInterval(funRef.current);
};
}, []);
for more: timer app
Upvotes: 5
Reputation: 798
You didn't really give us much of a context to work with (e.g. what do you mean by "leave the component"?), so we're kinda shooting in the dark.
However, as a first step, you could try declaring the timer
variable globally:
let timer; // <- put here
useEffect(() => {
timer = window.setInterval(() => {
refreshSave();
}, 3000);
return () => {
window.clearInterval(timer);
};
}, []);
Upvotes: 1