react useDebounce

PHOTO EMBED

Mon Aug 09 2021 18:29:41 GMT+0000 (UTC)

Saved by @amadogui #javascript #react.js

import { useCallback, useRef } from 'react';
export default function useDebounce(callback, delay = 400) {
  const debounce = useRef(null);
  return useCallback(
    (...args) => {
      const context = this;
      clearTimeout(debounce.current);
      debounce.current = setTimeout(() => {
        callback.apply(context, args);
      }, delay);
    },
    [callback, delay],
  );
}

/* 
Usage:

const handleWindowResize = useDebounce(SetWindow)

useEffect(() => {
window.addEventListener('resize', handleResize)
*/
content_copyCOPY