useInterval
function useInterval(callback: () => void, delayMs: number | null): void;
Calls callback every delayMs milliseconds. Pass null to pause. Any delay that is not a
positive, finite number also pauses, because a 0 ms interval would run as fast as the browser
allows. Changing delayMs restarts the interval. The latest callback is always called
without restarting it, so inline functions are fine.
Live demo
0.0 s
Example
import { useState } from "react";
import { useInterval } from "react-honey-hooks";
function Stopwatch() {
const [seconds, setSeconds] = useState(0);
const [running, setRunning] = useState(false);
useInterval(
() => {
setSeconds((s) => s + 1);
},
running ? 1000 : null,
);
return (
<button
onClick={() => {
setRunning((r) => !r);
}}
>
{seconds}s, {running ? "pause" : "start"}
</button>
);
}