20
loading...
This website collects cookies to deliver better user experience
setInterval
just doesn’t work as you’d expect. We will also learn to use it in a more declarative way. More on that later, let's focus on our flipbook nostalgia.setInterval
and he also insists to make it more declarative because you can make arguments “dynamic”, give that blog a read you will understand.function useInterval(callback, delay) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
});
useEffect(() => {
function tick() {
savedCallback.current();
}
let id = setInterval(tick, delay);
return () => clearInterval(id);
}, [delay]);
}
useInterval
is overkill for this case but I hope you got something out of it which can help you in future with imperative setInterval
pesky behaviour.