1

I'm new here to React. So the code here updates the value of height(whenever the screen size changes) after every refresh. Really confused as to why is it happenning since setHeight is not being used to update the value of height.

 import React, { useState } from "react";

 import "./styles.css";

 export default function App() {
 const [height, setHeight] = useState(window.innerHeight);


 return (
    <div className="App">
    <h1>
        {height}
        </h1>
        </div>
    );
 }
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • after a refresh, the browser renders your page again and any Javascript code in it is rerun - including the React code that renders your component. As a result, your component function is rerun so `window.innerHeight` is read and used as the initial `height` state. It never changes after that (till you reload again), even if the screen size changes, because you never call `setHeight` in your component. – Robin Zigmond Nov 05 '22 at 14:58

1 Answers1

1

A React component only rerender when a prop or its state got updated.

In your example, window.innerHeight is read at component initialization and placed in the state height. The only way to rerender your component is to have a listener on your variable (window.addEventListener) that will trigger an update by setting the state.

A working example following Rerender view on browser resize with React

 export default function App() {
   const [height, setHeight] = useState(window.innerHeight);

   useLayoutEffect(() => {
    function updateHeight() {
      setHeight(window.innerHeight);
    }
    window.addEventListener('resize', updateHeight);
    updateSize();
    return () => window.removeEventListener('resize', updateHeight);
   }, []);

   return (
    <div className="App">
      <h1>
        {height}
      </h1>
    </div>
    );
}
Antonin Riche
  • 548
  • 6
  • 10