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'23function useDebounce<T>(value: T, delay?: number): T {4 const [debouncedValue, setDebouncedValue] = useState<T>(value)56 useEffect(() => {7 const timer = setTimeout(() => setDebouncedValue(value), delay || 500)89 return () => {10 clearTimeout(timer)11 }12 }, [value, delay])1314 return debouncedValue15}1617export default useDebounce
Usage
1import { ChangeEvent, useEffect, useState } from 'react'23import { useDebounce } from 'usehooks-ts'45export default function Component() {6 const [value, setValue] = useState<string>('')7 const debouncedValue = useDebounce<string>(value, 500)89 const handleChange = (event: ChangeEvent<HTMLInputElement>) => {10 setValue(event.target.value)11 }1213 // Fetch API (optional)14 useEffect(() => {15 // Do fetch here...16 // Triggers when "debouncedValue" changes17 }, [debouncedValue])1819 return (20 <div>21 <p>Value real-time: {value}</p>22 <p>Debounced value: {debouncedValue}</p>2324 <input type="text" value={value} onChange={handleChange} />25 </div>26 )27}
See a way to make this page better?
Edit there »