raddix

useInterval

The useInterval hook is used to create an interval that executes a function every specified number of milliseconds. It is similar to the setInterval function, but it is declarative and can be cancelled.

Features

  • The interval is automatically cleared when the component is unmounted.
  • You can temporarily pause the interval by setting the value of delay to null.
  • When the callback changes, the interval is not reset.
  • When the delay changes, the interval is reset.
  • The interval is executed immediately on the first run, unless immediate is set to false.

Installation

npm i @raddix/use-interval

Usage

Basic example

Create a counter that increments every second.

import { useState } from 'react';
import { useInterval } from '@raddix/use-interval';
export const Counter = () => {
const [count, setCount] = useState(0);
useInterval(() => {
setCount(count + 1);
}, 1000);
return <span>{count}</span>;
};

Pause and resume

Create a counter that increments every second, but can be paused and resumed.

import { useState } from 'react';
import { useInterval } from '@raddix/use-interval';
export const Counter = () => {
const [count, setCount] = useState(0);
const { clear, run } = useInterval(() => {
setCount(count + 1);
}, 1000);
return (
<>
<span>{count}</span>
<button onClick={clear}>Pause</button>
<button onClick={run}>Resume</button>
</>
);
};

API

Parameters

The hook accepts the following parameters:

ParameterDescriptionRequiredType
funcThe function to be executed each time the interval elapses.Yesfunction
delayThe time, in milliseconds, the interval should wait before executing the function again. If `null`, the interval is paused.Yesnumber
immediateWhether the interval should be executed immediately on the first run. Defaults to `true`.Noboolean

Return value

The hook returns an object with the following properties:

PropertyDescriptionType
clearA function that can be called to clear the interval.function
runA function that can be called to execute the intervalfunction