Debounces the given value.
value
and a delay
.useState()
hook to store the debounced value.useEffect()
hook to update the debounced value every time value
is updated.setTimeout()
to create a timeout that delays invoking the setter of the previous state variable by delay
ms.clearTimeout()
to clean up when dismounting the component.const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = React.useState(value);
React.useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value]);
return debouncedValue;
};
const Counter = () => {
const [value, setValue] = React.useState(0);
const lastValue = useDebounce(value, 500);
return (
<div>
<p>
Current: {value} - Debounced: {lastValue}
</p>
<button onClick={() => setValue(value + 1)}>Increment</button>
</div>
);
};
ReactDOM.render(<Counter />, document.getElementById('root'));
Would you like to help us improve 30 seconds of code?Take a quick survey
React, Hooks
Checks if the current environment matches a given media query and returns the appropriate value.
React, Hooks
Returns a stateful value, persisted in localStorage
, and a function to update it.
React, Hooks
Tracks the browser's location hash value, and allows changing it.