Skip to contentVibraUI
Foundation

useInterval

Runs a callback on a fixed interval, pausable by passing null, always calling its latest version.

The callback is stored in a ref, so changing it never resets or duplicates the underlying interval.

Install

npx shadcn@latest add @vibra/use-interval

Needs the @vibra registry in your components.json — set it up once.

Examples

Props

PropTypeDefaultDescription
callback() => void—Called on every tick; always the latest version passed in, never a stale closure.
delaynumber | null—Milliseconds between ticks; pass null to pause without tearing the interval down.

Dependencies

Registry

Source

hooks/use-interval.ts
import * as React from "react"

/** Runs `callback` every `delay` ms, always invoking its latest version (no stale closures); pass `null` to pause without tearing down. */
export function useInterval(callback: () => void, delay: number | null): void {
  const savedCallback = React.useRef(callback)

  React.useEffect(() => {
    savedCallback.current = callback
  }, [callback])

  React.useEffect(() => {
    if (delay === null) return
    const id = setInterval(() => savedCallback.current(), delay)
    return () => clearInterval(id)
  }, [delay])
}