useDebounce()

This React hook helps to limit that the component is re-rendered too many times. Imagine that you want to execute a function on an event that executes several hundred times per second such as moving the mouse or scrolling. This may cause the application to lag. To prevent this, the debounce uses an internal timer to execute the callback function every xx seconds (2nd parameter).

Consider the example below. Each time the user enters the field, the onChange event is triggered. On the other hand, the unfolded variable is updated at most every 500ms. If you have to make an API call to find the elements that match the search term, you can do so by monitoring the unpacked variable, which will be more economical.

The Hook

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

Usage

1import { ChangeEvent, useEffect, useState } from 'react'
2
3import { useDebounce } from 'usehooks-ts'
4
5export default function Component() {
6 const [value, setValue] = useState<string>('')
7 const debouncedValue = useDebounce<string>(value, 500)
8
9 const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
10 setValue(event.target.value)
11 }
12
13 // Fetch API (optional)
14 useEffect(() => {
15 // Do fetch here...
16 // Triggers when "debouncedValue" changes
17 }, [debouncedValue])
18
19 return (
20 <div>
21 <p>Value real-time: {value}</p>
22 <p>Debounced value: {debouncedValue}</p>
23
24 <input type="text" value={value} onChange={handleChange} />
25 </div>
26 )
27}

Edit on CodeSandbox

See a way to make this page better?
Edit there »