h3/use's logo

h3/use

Command Palette

Search for a command to run...

useInterval

Runs a callback at specified intervals.

useInterval
This component uses the useInterval hook to increment a counter every second.

Count: 0

Installation

Props

PropTypeDefaultDescription
callback() => void() => {}The function to execute at each interval.
delaynumber | nullnullThe delay in milliseconds between each execution.

Key Features & Details

  • The hook sets up an interval using setInterval and cleans up with clearInterval.
  • Passing null as delay pauses the interval.
  • Ensures the latest callback is always invoked by using a ref.

Examples

Basic Usage

import { useInterval } from '@/registry/hooks/use-interval';
 
function Component() {
  useInterval(() => {
    console.log('tick');
  }, 1000);
 
  return <div>Check the console for ticks every second.</div>;
}

Pause and Resume

import { useState } from 'react';
 
import { useInterval } from '@/registry/hooks/use-interval';
 
function Timer() {
  const [count, setCount] = useState(0);
  const [active, setActive] = useState(true);
 
  useInterval(() => setCount((c) => c + 1), active ? 1000 : null);
 
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setActive((a) => !a)}>
        {active ? 'Pause' : 'Resume'}
      </button>
    </div>
  );
}