DEV Community

Discussion on: Developing responsive layouts with React Hooks

Collapse
 
jannikwempe profile image
Jannik Wempe

Thanks for the awesome article. I learned something and love hooks more and more ;) Adding throttling would make it an awesome solution as a drop in to various projects...

I couldn't make it work with lodashs throttling (there is no actual throttling in my solution). Here is what i got:

 React.useEffect(() => {
    const handleWindowResize = () => {
      console.log(count); // just a counter I added as a state
      setWidth(window.innerWidth);
      setHeight(window.innerHeight);
      setCount(prevCount => prevCount + 1);
    };
    const throttledHandleWindowResize = _.throttle(handleWindowResize, 1000);

    window.addEventListener("resize", throttledHandleWindowResize);

    return () =>
      window.removeEventListener("resize", throttledHandleWindowResize);
  }, [count]);

I guess it is because every time count changes a new event listener is attached and therefore throttling never happens. Am I right? What would be the solution? I guess it is something using useRef()? But I don't get it...

Collapse
 
benhoneywill profile image
Ben Honeywill • Edited

Hey Jannik, author here. Sorry for the very late reply I wasn't aware that my article was posted here 🙂 I'm glad you found it useful!

You are right, every time you are updating count your useEffect is going to rerun and a different event listener is going to be added every time. Moving your event listener outside of the effect should solve this for you!

You might also want to make use of useCallback, so that you can safely pass the function into the effect as a dependency - it would look something like this:

const throttledHandleWindowResize = React.useCallback(
    _.throttle(() => {
      setWidth(window.innerWidth);
      setHeight(window.innerHeight);
    }, 1000),
    [setWidth, setHeight]
);

React.useEffect(() => {
    window.addEventListener("resize", throttledHandleWindowResize);
    return () => window.removeEventListener("resize", throttledHandleWindowResize);
}, [throttledHandleWindowResize]);

Here are the useCallback docs, if you want to have a read about this 🙂Thanks for reading!