useInterval
@volvo-cars/react-utils v2.0.0
Calls a function repeatedly at a fixed delay using setInterval. The interval is cleared when the component unmounts or the delay changes. The hook always calls the latest callback, so changing the callback does not restart the interval.
Update a countdown every second:
import { useState } from 'react';import { useInterval } from '@volvo-cars/react-utils';
function Countdown() { const [seconds, setSeconds] = useState(10);
useInterval( () => setSeconds((value) => value - 1), seconds > 0 ? 1000 : null, );
return <p>{seconds}</p>;}Pass null as the delay to pause the interval.
useInterval(callback, delay) accepts:
callback: function to call on every tickdelay: time between calls in milliseconds, ornullto stop the interval
Returns nothing.