Implement the useWindowSize Hook
To get started, open the editor. You can see the following files from your editor.
├── package-lock.json
├── package.json
├── public
│ ├── index.html
│ └── robots.txt
└── src
├── App.css
├── App.js
├── hooks
│ └── useWindowSize.js
├── index.css
├── index.js
├── reportWebVitals.js
└── setupTests.js
In this step, you will learn how to implement the useWindowSize custom Hook to get the current window size.
- Open the
useWindowSize.js file located in the src/Hooks directory.
- In this file, import the necessary dependencies:
import { useEffect, useState } from "react";
- Define the
useWindowSize function:
import { useEffect, useState } from "react";
export const useWindowSize = () => {
const [windowSize, setWindowSize] = useState({
width: window.innerWidth,
height: window.innerHeight
});
const changeWindowSize = () => {
setWindowSize({ width: window.innerWidth, height: window.innerHeight });
};
useEffect(() => {
window.addEventListener("resize", changeWindowSize);
return () => {
window.removeEventListener("resize", changeWindowSize);
};
}, []);
return windowSize;
};
Explanation:
- The
useWindowSize function returns an object containing the current window width and height.
- The
useState hook is used to create a state variable windowSize and a function setWindowSize to update it.
- The
changeWindowSize function is defined to update the windowSize state when the window is resized.
- The
useEffect hook is used to add an event listener for the resize event and remove it when the component is unmounted.
- The
windowSize object is returned from the useWindowSize function.