typescriptintermediate
useInterval Hook
Declarative setInterval hook that handles cleanup and dynamic delay changes safely.
typescriptPress ⌘/Ctrl + Shift + C to copy
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]);
}Use Cases
- Polling APIs
- Countdown timers
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
useTimeout Hook
Declarative setTimeout hook with automatic cleanup and reset capabilities.
Best for: Auto-dismiss notifications
#hooks#timer
typescriptbeginner
usePrevious Hook
Track the previous value of any state or prop using a ref-based hook for comparison logic.
Best for: Detecting value changes
#hooks#state
typescriptintermediate
React Custom Hook for Data Fetching
A reusable useFetch hook with loading states, error handling, caching, and abort support.
Best for: Reusable data fetching across components
#react#hooks
typescriptintermediate
React Form Validation Hook
A type-safe form validation hook with field-level errors, dirty tracking, and submit handling.
Best for: Type-safe form handling without libraries
#react#forms