Back to Digest
SnippetsTypeScript useDebounce Hook with Immediate Execution
typescriptAdvancedCopied 140 times

TypeScript useDebounce Hook with Immediate Execution

A generic, type-safe debounced value and callback hook with cancel, flush, and immediate trigger capabilities.

typescript•
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { useState, useEffect, useRef, useCallback } from 'react'; export function useDebounce<T>(value: T, delay: number, immediate = false): T { const [debouncedValue, setDebouncedValue] = useState<T>(value); const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null); useEffect(() => { if (immediate && !timerRef.current) { setDebouncedValue(value); } timerRef.current = setTimeout(() => { setDebouncedValue(value); timerRef.current = null; }, delay); return () => { if (timerRef.current) clearTimeout(timerRef.current); }; }, [value, delay, immediate]); return debouncedValue; }
23 lines • 653 charactersUsed by 140 developers

Usage & Production Best Practices

This implementation is specifically optimized for high-throughput production environments. When integrating this pattern into your codebase:

  • Ensure all asynchronous handles or listeners are cleaned up within the parent lifecycle.
  • Avoid unbounded memory allocation by pinning cache buffers and queue capacities.
  • Pair with automated unit tests to guarantee zero regressions under edge-case concurrency.
Featured Resourcein React / TypeScript
Curated Tool