Rehooks

useInterval

Sets up an interval with imperative controls. Returns start/stop methods and running state.

useInterval

Installation

npx rehooks-cli@latest add useInterval

Usage

Component.tsx
import { useInterval } from "~/hooks/useInterval";
 
function Component() {
  const { start, stop, toggle, isRunning } = useInterval(
    () => {
      console.log("Interval tick!");
    },
    1000,
    { autoStart: true },
  );
 
  return (
    <div>
      <button onClick={start}>Start</button>
      <button onClick={stop}>Stop</button>
      <button onClick={toggle}>Toggle</button>
      <p>Is running: {isRunning ? "Yes" : "No"}</p>
    </div>
  );
}

API

useInterval

useInterval.ts
function useInterval(
  callback: () => void,
  delay: number | null,
  options?: IntervalOptions,
): IntervalReturn;

Sets up an interval with imperative controls. Returns start/stop methods and running state.

Parameters

NameTypeDescription
callback() => voidFunction to execute at each interval tick (automatically uses latest version)
delaynumber | nullInterval delay in milliseconds (null to clear interval)
optionsIntervalOptionsOptional configuration for the interval
immediatebooleanIf true, the callback function will be executed immediately after the interval starts (default: false)
autoStartbooleanIf true, the interval will start automatically (default: true)

Returns

NameTypeDescription
startvoid
stopvoid
togglevoid
isRunningboolean

On this page