react-usekit

Beta

useInterval

A custom hook that sets up an interval to call a callback function at specified intervals.

Installation

npx react-usekit@latest init

Select: hooks → TypeScript or JavaScript → path -> useInterval

Usage

import { useInterval } from "./hooks/useInterval";
import { useState } from "react";

function Timer() {
  const [count, setCount] = useState(0);
  const [isRunning, setIsRunning] = useState(true);

  useInterval(
    () => {
      setCount(count + 1);
    },
    isRunning ? 1000 : null
  );

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setIsRunning(!isRunning)}>
        {isRunning ? "Pause" : "Start"}
      </button>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

Pass null as the delay to pause the interval. The hook automatically cleans up the interval when the component unmounts.

API

Parameters

ParameterTypeDescription
callback() => voidThe function to be called at each interval
delaynumber | nullThe time in milliseconds between calls. If null, the interval is paused

Returns

This hook doesn't return anything.