DEV Community

Discussion on: Developing responsive layouts with React Hooks

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!