React useWindowSize Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38416{{"`React useWindowSize Hook`"}} react/hooks -.-> lab-38416{{"`React useWindowSize Hook`"}} react/use_state_reducer -.-> lab-38416{{"`React useWindowSize Hook`"}} end

React useWindowSize Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To track the dimensions of the browser window, the following steps can be taken:

  1. Use the useState() hook to initialize a state variable windowSize that will hold the window's dimensions. Initialize with both values set to undefined to avoid mismatch between server and client renders.
const [windowSize, setWindowSize] = React.useState({
  width: undefined,
  height: undefined
});
  1. Create a function handleResize() that uses Window.innerWidth and Window.innerHeight to update the state variable. This function will be called whenever the 'resize' event is triggered.
const handleResize = () =>
  setWindowSize({ width: window.innerWidth, height: window.innerHeight });
  1. 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.

Other React Tutorials you may like