Write a Custom React Hook that Returns the Browser's Width and Height

Share this video with your friends

Send Tweet

In this lesson, you'll learn how to write a custom React hook that returns the browser's inner width and inner height. We're going to call it useWindowSize.

We first import useState to keep track of the state of the browser window.

We also create a function called getSize( ) that returns an object containing the browser's inner width and inner height from the window object.

We then create a variable called windowSize, a function that will update it called setWindowSize and we set the initial value of our state by calling the getSize( ) function.

Next, we create a function called useWindowSize, and inside of it, we use the useEffect hook.

Inside our useEffect hook, we add an event listener to the window object, that listens to the resize event and will invoke a function called handleResize( ) every time the window is resized. We then return a function that removes this event listener.

The handleResize( ) function updates the state by calling setWindowSize and passing the getSize( ) function to it.

Finally, we return windowSize, which will be an object that contains the browser's inner width and inner height.