React Dojo

Search

Search concepts, exercises and quizzes

utility

useInterval

Declarative wrapper around setInterval that always syncs the latest callback without manual cleanup.


useInterval.ts
import { useEffect, useRef } from "react"

export function useInterval(callback: () => void, delay: number | null) {
  const savedCallback = useRef(callback)

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

  useEffect(() => {
    if (delay === null) return
    const id = setInterval(() => savedCallback.current(), delay)
    return () => clearInterval(id)
  }, [delay])
}
Was this helpful?
Sign in to give feedback