Reputation: 33
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>
);
}
Upvotes: 1
Views: 60
Reputation: 578
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>
);
}
Upvotes: 1