useDebounce
The useDebounce
Hook allows you to debounce a value so that it is only updated after a certain delay has passed.
Here's an example:
import { useState, useEffect } from 'react'
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value)
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => {
clearTimeout(timer)
}
}, [value, delay])
return debouncedValue
}
function MyComponent() {
const [inputValue, setInputValue] = useState('')
const debouncedValue = useDebounce(inputValue, 500)
function handleChange(event) {
setInputValue(event.target.value)
}
return (
<div>
<input type="text" value={inputValue} onChange={handleChange} />
<p>Debounced value: {debouncedValue}</p>
</div>
)
}
In this example, we define a useDebounce
Hook that takes a value
and a delay
and returns a debounced value that is only updated after the specified delay has passed. We use the useState
Hook to create a debouncedValue
state variable and the useEffect
Hook to set a timer that updates the debouncedValue
after the specified delay has passed. We also use the useEffect
Hook to clean up the timer when the value
or delay
changes. Inside our component, we render an input
element that updates the inputValue
state variable when its value changes. We also render the current value of debouncedValue
.