Skip to content

useInterval

useInterval is a React hook that executes a function at a specified interval. It is useful for timers, polling data, and other recurring tasks.

Interface

ts
function useInterval(
  callback: () => void,
  options: number | { delay: number; enabled?: boolean; immediate?: boolean }
): void;

Parameters

  • callbackrequired · () => void

    The function to be executed periodically.

  • optionsrequired · number | { delay: number; enabled?: boolean; immediate?: boolean }

    Configures the interval behavior.

    • options.delaynumber

      The interval duration in milliseconds. If null, the interval will not run.

    • options.immediateboolean · false

      If true, executes immediately before starting the interval.

    • options.enabledboolean · true

      If false, the interval will not run.

Return Value

This hook does not return anything.

Example

tsx
import { useInterval } from 'react-simplikit';
import { useState } from 'react';

function Timer() {
  const [time, setTime] = useState(0);

  useInterval(() => {
    setTime(prev => prev + 1);
  }, 1000);

  return (
    <div>
      <p>{time} seconds</p>
    </div>
  );
}

Released under the MIT License.