Languages
[Edit]
EN

React - rerender component on browser resize

0 points
Created by:
mkrieger1
726

In this article, we would like to show you how to rerender component on browser resize in React.

Rerender component on browser resize example
Rerender component on browser resize example

In the example below, we use the useState and useEffect hooks. We store the current window dimensions in the component state.

Run the example below and resize the window to see the result.

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from "react";
// import ReactDOM from "react-dom";

const App = () => {
  const [dimensions, setDimensions] = React.useState({
    height: window.innerHeight,
    width: window.innerWidth
  })
  const handleResize = () => {
    setDimensions({
      height: window.innerHeight,
      width: window.innerWidth
    });
  }
  React.useEffect(() => {
    window.addEventListener('resize', handleResize)
    return () => { window.removeEventListener('resize', handleResize) }
  });
  return (
    <div>
      <p>Window height: {dimensions.height} </p>
      <p>Window width: {dimensions.width} </p>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

Now let's follow this code step by step:

  1. dimensions state initialization - an object with the current window height and width assigned.
  2. Component rendering.
  3. When the window size changes, addEventListener catches it and calls the handleResize method.
  4. handleResize method using setDimensions changes the stored window dimensions to the current one.
  5. The component re-renders.

See also: 

  1. useEffect hook

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join