Skip to content
Advertisement

Why does lodash throttle not work within the useWindowSize custom hooks?

I’m trying to use resize event with throttle. However, it doesn’t work. I tried to debug it as follow:

import {throttle} from 'lodash'

export function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  })

  const handleResize = () => {
    // handle resize code....
  }

  const onWindowResize = () => {
    console.log('Throttle') // <-- this does print out
    throttle(() => {
      console.log('bam') // <-- this doesn't print out
    }, 100)
  }

  useEventListener('resize', onWindowResize)

  return windowSize
}

As seen from the code above, I’ve been trying to log out before I use the throttle func from lodash. It does print out, but the log inside the throttle itself doesn’t. Anyone knows why this maybe and how to fix this?

Advertisement

Answer

Your inline function recrated on every render. Just make sure the throttle function will be the same function on next render. You can use useCallback hook.

export function useWindowSize() {
   const [windowSize, setWindowSize] = useState({
     width: undefined,
     height: undefined
  });
  const someFunction = (e) => {
     console.log("bam", e); // 
  };
  const throttleFn = useCallback(throttle(someFunction, 1000), []);

  const onWindowResize = (e) => {
     console.log("Throttle", e); 
     throttleFn(e);
  };

  useEventListener("resize", onWindowResize);

  return windowSize;
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement