Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
}
about 4 years ago · Juan Pablo Isaza Report

0

I've been trying to solve this and something similar as the following code works for me:

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

  const handleResize = useCallback(() => {
    console.log('handleResize') // It does log this out
    // handle the resize...
  }, [windowSize])


  useEventListener('resize', throttle(handleResize, 4000)) // call it here instead
  return windowSize
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!