DEV Community

Discussion on: Debouncing with React Hooks

Collapse
 
ruchitgandhineu profile image
Ruchit Gandhi

Loved the explanation. Thanks!
Although I would use useRef hook to set the timer variable to reduce the heap memory usage.

const useDebounce = (value, delay = 500) => {
  const [debouncedValue, setDebouncedValue] = useState();
  const timer = useRef(null);
  useEffect(() => {
    timer.current = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);
    return () => clearTimeout(timer.current);
  }, [value, delay]);

  return debouncedValue;
};
Enter fullscreen mode Exit fullscreen mode

Edit how-to-use-debounce