useInterval
A React hook for creating declarative intervals with automatic cleanup. Under the hood, it uses the setInterval API.
- Installation
- Add Source Code
npm install @plenty-hooks/use-interval
npx @plenty-hooks/cli use-interval
Using this command will add the source code of the hook directly to your project.
Options:
--pathor-p: Specify the directory where the hook file should be saved--kebab-caseor-k: Use kebab-case for the output filename (e.g.,use-document-title.ts). By default, the filename uses camelCase (e.g.,useDocumentTitle.ts)
Note: By adding the source code of the hook directly to your project, you won't be able to install further updates automatically. You are on your own for maintaining and updating the code.
Showcase
import { useState } from 'react';
import useInterval from '@plenty-hooks/use-interval';
function Counter() {
const [count, setCount] = useState(0);
const [delay, setDelay] = useState<number | null>(1000);
useInterval(() => {
setCount((c) => c + 1);
}, delay);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setDelay(1000)}>Start</button>
<button onClick={() => setDelay(null)}>Stop</button>
</div>
);
}
API
useInterval(callback, delay)
Creates an interval that calls the provided callback function at the specified delay. The interval automatically cleans up when the component unmounts or when the delay changes.
Parameters
callback: () => void- The function to be called at each interval.delay: number | null | undefined- The delay in milliseconds between each callback invocation. Passnullorundefinedto pause/disable the interval.
Returns
void- This hook does not return any value.