const [schedule, cancel] = useInterval();
useEffect(() => {
// Cancels currently scheduled callback and schedules the new one
schedule(
(a, b) => {
doSomething(a, b);
},
500, // Interval delay
a, b, // Varargs that are passed to the callback
);
// Stops invoking the callback that was last provided to schedule()
cancel();
}, []);
The replacement for
window.setInterval
that schedules a function to be repeatedly called with a fixed time delay between each call. Interval is cancelled when component is unmounted or when a new interval is scheduled.All functions that were scheduled with the same delay are invoked synchronously across all components that use this hook.
Intervals must be scheduled/canceled after the component is mounted. Before that, it is a no-op.