Resize event listener using React hooks

Vitalie Maldur
BluePixel
Published in
2 min readJan 14, 2020

--

Photo by Thomas Tastet on Unsplash

A couple of weeks ago while I was working on a small React project I had to implement some custom logic for the scenario when the user resizes the browser window.

The usual Javascript solution looks like this.

This one can be used successfully, but it is not looking very good in a React app. So I decided to implement it differently using a more familiar approach for React developers, called hooks. Hooks are functions that let you “hook into” React state and lifecycle features from function components.

A hook that will return the window width and update it when it changes can look like this.

I used useState hook to keep window width value in the state object and useEffect to add a listener for the resize event.

There is one more thing to mention, resize event it is triggered multiple times while the user is actively dragging the browser’s window resize handle, it may affect the performance of your application if you have a complex logic in the resize listener. One way to deal with it is to implement some debounce mechanism that will limit the rate at which a function can fire.

How this debounce mechanism works? At every resize event fired, we delay the changing of the state object with 150 milliseconds, in case that another resize event gets fired before, it will prevent the previous change of the state to happen. In other words, the change of the state can happen only once every 150 milliseconds. More about this technique you can read on David Walsh blog.

Example of how to use this hook in a React component.

Complete source code can be found here. Original article on dev.to 👉https://dev.to/vitaliemaldur/resize-event-listener-using-react-hooks-1k0c

Liked the article?

We’re always looking for a great project to work on, so don’t hesitate to drop us a line at hello[at]bluepixelgroup.com or visit our website: https://bluepixelgroup.com

--

--