From f749d598995f0f5d041938522d58be2da6c617d5 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Mon, 4 Jan 2021 16:48:43 +0200 Subject: [PATCH] Add useDebounce --- snippets/useDebounce.md | 49 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 snippets/useDebounce.md diff --git a/snippets/useDebounce.md b/snippets/useDebounce.md new file mode 100644 index 000000000..13129224d --- /dev/null +++ b/snippets/useDebounce.md @@ -0,0 +1,49 @@ +--- +title: useDebounce +tags: hooks,state,effect,intermediate +--- + +Debounces the given value. + +- Create a custom hook that takes a `value` and a `delay`. +- Use the `useState()` hook to store the debounced value. +- Use the `useEffect()` hook to update the debounced value every time `value` is updated. +- Use `setTimeout()` to create a timeout that delays invoking the setter of the previous state variable by `delay` ms. +- Use `clearTimeout()` to clean up when dismounting the component. +- This is particularly useful when dealing with user input. + +```jsx +const useDebounce = (value, delay) => { + const [debouncedValue, setDebouncedValue] = React.useState(value); + + React.useEffect(() => { + const handler = setTimeout(() => { + setDebouncedValue(value); + }, delay); + + return () => { + clearTimeout(handler); + }; + }, [value]); + + return debouncedValue; +}; +``` + +```jsx +const Counter = () => { + const [value, setValue] = React.useState(0); + const lastValue = useDebounce(value, 500); + + return ( +
+

+ Current: {value} - Debounced: {lastValue} +

+ +
+ ); +}; + +ReactDOM.render(, document.getElementById('root')); +```