Introduction
In this lab, we will learn how to use the useWindowSize hook in React to track the dimensions of the browser window. This hook enables us to create responsive designs and adjust the layout of our components based on the size of the user's screen. By the end of this lab, you will have a better understanding of how to use hooks in React and how to create more user-friendly applications.
React useWindowSize Hook
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
To track the dimensions of the browser window, the following steps can be taken:
- Use the
useState()hook to initialize a state variablewindowSizethat will hold the window's dimensions. Initialize with both values set toundefinedto avoid mismatch between server and client renders.
const [windowSize, setWindowSize] = React.useState({
width: undefined,
height: undefined
});
- Create a function
handleResize()that usesWindow.innerWidthandWindow.innerHeightto update the state variable. This function will be called whenever the'resize'event is triggered.
const handleResize = () =>
setWindowSize({ width: window.innerWidth, height: window.innerHeight });
- Use the
useEffect()hook to set an appropriate listener for the'resize'event on mount and clean it up when unmounting.
React.useEffect(() => {
window.addEventListener("resize", handleResize);
handleResize();
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
Putting it all together, the useWindowSize() custom hook can be defined as follows:
const useWindowSize = () => {
const [windowSize, setWindowSize] = React.useState({
width: undefined,
height: undefined
});
const handleResize = () =>
setWindowSize({ width: window.innerWidth, height: window.innerHeight });
React.useEffect(() => {
window.addEventListener("resize", handleResize);
handleResize();
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
return windowSize;
};
To use the useWindowSize() hook, simply call it in a component and destructure the width and height values from the returned object.
const MyApp = () => {
const { width, height } = useWindowSize();
return (
<p>
Window size: ({width} x {height})
</p>
);
};
ReactDOM.createRoot(document.getElementById("root")).render(<MyApp />);
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the React useWindowSize Hook lab. You can practice more labs in LabEx to improve your skills.