useInterval

Setup an interval playing nicely with the hooks api. The implementation is shamelessly copied from Dan Abramov.

Usage

import React, { useState } from 'react';
import { useInterval } from '@fransvilhelm/hooks';
const Counter = () => {
const [run, setRun] = useState(false);
const [count, setCount] = useState(0);
useInterval(() => setCount(count + 1), run ? 1000 : null);
return (
<div>
<button onClick={() => setRun(!run)}>{run ? 'Pause' : 'Play'}</button>
<output>{count}</output>
</div>
);
};

Example

0

Parameters

useInterval accepts two parameters – the callback to run on the interval and a number representing the delay. The delay might be null in order to stop the interval.

ParamTypeRequiredDefaultDescription
callbackfunctiontrue-Callback to run on every interval
delaynumber | nulltrue-The time between intervals. Use null to stop the interval

Returns

useInterval nothing.