useDebounce

Debounces a value, delaying its update until a specified time has passed without further changes.

Code

1import { useState, useEffect } from "react"
2
3export function useDebounce<T>(value: T, delay: number): T {
4  const [debouncedValue, setDebouncedValue] = useState<T>(value)
5
6  useEffect(() => {
7    const handler = setTimeout(() => {
8      setDebouncedValue(value)
9    }, delay)
10
11    return () => {
12      clearTimeout(handler)
13    }
14  }, [value, delay])
15
16  return debouncedValue
17}

Usage Example

import { useState } from "react" import { useDebounce } from "@/hooks/use-debounce" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" export function DebounceExample() { const [inputValue, setInputValue] = useState("") const debouncedSearchTerm = useDebounce(inputValue, 500) return ( <div className="space-y-4"> <Label htmlFor="search-input">Search (debounced by 500ms)</Label> <Input id="search-input" placeholder="Type to search..." value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> <p className="text-sm text-npui-muted-foreground">Debounced Value: {debouncedSearchTerm}</p> </div> ) }