DEV Community

Discussion on: Using Lodash Debounce with React Hooks for an Async Data Fetching Input or use a Custom Hook.

Collapse
 
jackzhoumine profile image
jackzhoumine • Edited

no need loash actuall.

use this hook

function useDebounce(value, wait = 200) {
  const [debounceValue, setDebounceValue] = setState(value);
  useEffect(() => {
    const timer = setTime(() => {
      setDebounceValue(value);
    }, wait);
    return () => clearTimeout(timer);
  }, [value, wait]);
  return debounceValue;
}
// use useDebounce
const [input, setInput] = setState();
const debounceInput = useDebounce(input);
useEffect(() => {
  //http with debounceInput
}, [debounceInput]);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
alexdrocks profile image
Alexandre Desroches • Edited

Thanks for sharing Jackzhoumie. I'll try your solution today. Note: for my test I was required to use Lodash's debounce that's why I had such a strong focus on using it.

Collapse
 
alexdrocks profile image
Alexandre Desroches • Edited

Actually you are right, I managed to make a working example on the same Codesandbox project: codesandbox.io/s/react-debounced-d...

So you can avoid importing Lodash debounce and it works just about the same. The only difference I see is that you have to handle the initial render to NOT trigger the debounced function call. PS: I edited my original post to include this solution.