All files / src/hooks useDebouncedValue.ts

100% Statements 7/7
100% Branches 1/1
100% Functions 4/4
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18                206x   206x 113x 113x     206x    
import { useEffect, useState } from 'react'
 
/**
 * Debounces a fast-changing value (e.g. a search input) so consumers (a
 * client-side `.filter()`, a future server `?search=` request) only react
 * once the user pauses typing, instead of on every keystroke.
 */
export function useDebouncedValue<T>(value: T, delayMs = 300): T {
  const [debouncedValue, setDebouncedValue] = useState(value)
 
  useEffect(() => {
    const timeoutId = setTimeout(() => setDebouncedValue(value), delayMs)
    return () => clearTimeout(timeoutId)
  }, [value, delayMs])
 
  return debouncedValue
}