React Tutorials

React Get Dynamic Window Height Width using React Hooks

React Js get window height width on window resize tutorial; In this tutorial, we will help you find out how to use React useState and useEffect hooks to detect the dynamic window width and height on window resize.

React hooks are fantastic, they help you use state and other essential react features in react functional components. Before we move forward, let’s understand what useState and useEffect hooks are.

useEffect: This hook orders React to take action after the component renders. It takes an array as a value; the value passed to the useEffect array will tell the useEffect hook to invoke only the change occurred in the passed array property. Otherwise, If you leave it empty, it will look for the change in the entire component.

On the other hand, useEffect offers a cleanup function; it works asynchronously and runs the cleanup function before performing a new effect. It unsubscribes the functions, values and boosts the component performance by preventing the memory leak.

useState: This hook helps you define the state variable in functional components. You set the initial state to this function, and it returns the variable with current state similarly the other function updates this value.

How to Use React Hooks to Detect Window Size in React Js

  • Step 1: Create React Project
  • Step 2: Create Component File
  • Step 3: Get Dynamic Screen Dimension on Resize
  • Step 4: Update App Js File
  • Step 5: Start React App

Create React Project

Let us create the react application using the create-react-app cli tool. You may jump on to the subsequent step if already installed the app.

npx create-react-app react-blog

After the app is created, get into the app.

cd react-blog

Create Component File

Next, create a UserWindow.js file, then copy and paste the provided code into the file.

import React, { Component } from "react";

class UserWindow extends Component {
  render() {
    return (
      <> </>
    );
  }
}

export default UserWindow;

Get Dynamic Screen Dimension on Resize

Import React, and useState, useEffect hooks from the ‘react’ package into the functional component. To set the initial state, use the useState hook.

The useEffect hook is here to call the setDimension function when the component renders; in our case, it will re-render when the user resizes the screen size.

In this step, you have to open the components/UserWindow.js file and insert the given below code.

import React, { useState, useEffect } from 'react'


export default function UserWindow() {

  const [screenSize, getDimension] = useState({
    dynamicWidth: window.innerWidth,
    dynamicHeight: window.innerHeight
  });

  const setDimension = () => {
    getDimension({
      dynamicWidth: window.innerWidth,
      dynamicHeight: window.innerHeight
    })
  }
  
  useEffect(() => {
    window.addEventListener('resize', setDimension);
    
    return(() => {
        window.removeEventListener('resize', setDimension);
    })
  }, [screenSize])

  return (
    <div>
      <ul>
        <li>Width: <strong>{screenSize.dynamicWidth}</strong></li>
        <li>Height: <strong>{screenSize.dynamicHeight}</strong></li>
      </ul>    
    </div>
  )
}

Update App Js File

Now, we can add the UserWindow component in the app js file. Open the src/App.js file and insert the given code code into the file.

import React from "react";
import UserWindow from "./components/UserWindow"


export default function App() {
  return (
    <UserWindow />
  );
}

Start React App

You can execute the following command to start the react app.

npm start

This url will help you open the app.

http://localhost:3000

Conclusion

In this tutorial, we discussed how you could take action when the component renders or re-renders. We used the concept of React hooks to find out the dynamic window height and width.

Particularly, we used the useState to set the initial height and width of the window. Also, used the useEffect hook to update the value when found the change in the screen size variable.

Digamber

I am Digamber, a full-stack developer and fitness enthusiast. I crafted this site to bestow my coding experience and love to write on JavaScript, React, Angular, Vue, Laravel.

Recent Posts

React Display Validation Error Messages with Hook Form Tutorial

As a React developer, you must know how to implement validation in form, and a…

2 days ago

React Hook Form 7 Required Checkbox Validation Tutorial

Creating checkboxes in React is not so difficult, especially when you are using React Hook…

5 days ago

React Hook Form 7 Custom Radio Buttons Tutorial

Learning React is not complicated; instead, it's easy, but only when you have the right…

1 week ago

React Bootstrap Custom Dropdown List with Fetch API Tutorial

Dropdown is a valuable and prominent module, which is often used to select one option…

2 weeks ago

React Hook Form Reset / Clear Form Values and Errors Tutorial

React form reset tutorial; Forms are handy provides the best possible way to get information…

2 weeks ago

React Show Loading Spinner on Submit Click Tutorial

You click on the submit button, form is processed, but nothing is being shown to…

2 weeks ago