useDebounced
Hooks used in this custom hook: useState
, useEffect
, and useRef
In Chapter 6, Use Memo to Boost Performance, we ran into a very interesting implementation where we debounced the user keystroke so that we don't invoke a heavy operation (such as search) too frequently.
A pattern that emerged is that for a given state, whenever we change it via dispatch, we want to wait for a period of time before we are assured that it's the right time to act upon it. So essentially we want to design a new state as a debounced version of a given state. Let's try to capture this pattern in a custom useDebounced
hook:
const useDebounced = (oldState, duration) => { const [state, dispatch] = useState(oldState) const invokeRef = useRef(null) useEffect(() => { invokeRef.current = setTimeout(() => { dispatch...