snippet
useDebouncedValue
snippet
useDebouncedValue
Last updated January 23rd, 2023
This hook allows us to debounce any fast-changing value. The debounced value will only reflect the latest value when the useDebouncedValue hook has not been called for a specified amount of time. Using this hook, we can easily ensure that expensive operations like API calls are not executed too frequently.
We first set up state and set the initial value to the value
that is passed into the hook. A timeout is then set inside of the useEffect
to ensure that the callback function is not executed until a specified amount of time has elapsed -- this is denoted by the delay
variable. We then clean up our useEffect
by clearing our timeout alongside ensuring that our useEffect
only runs when the value
or delay
variables change.
Finally, we return our debounced value.
We can see here that when we increment the count rapidly, the debounced value only updates to reflect the latest value after one (1) second of the button not being pressed.
import { useState, useEffect } from "react";
const useDebouncedValue = (value, delay) => {
const [debounceValue, setDebounceValue] = useState(value);
useEffect(() => {
const timeout = setTimeout(() => {
setDebounceValue(value);
}, delay);
return () => {
clearTimeout(timeout);
};
}, [value, delay]);
return debounceValue;
};
import useDebouncedValue from "./useDebouncedValue";
import { useState } from "react";
const App = () => {
const [count, setCount] = useState(0);
const debouncedValue = useDebouncedValue(count, 1000);
const incrementCount = () => {
setCount((prev) => prev + 1);
};
return (
<>
<button onClick={incrementCount}>Increment count</button>
<p>{count}</p>
<p>{debouncedValue}</p>
</>
);
};