Reputation: 33
import * as React from "react";
// import "./style.css";
export default function App() {
let [width, setWidth] = React.useState(window.innerWidth);
let [height, setHeight] = React.useState(window.innerHeight);
React.useEffect(() => {
console.log("useEffect is called");
window.addEventListener("resize", () => {
setHeight(window.innerHeight);
setWidth(window.innerWidth);
});
}, []);
return (
<div>
{/* <button onClick={handler}> Submit </button> */}
<h1>
{" "}
{height},{width}{" "}
</h1>
</div>
);
}
The above code causes re-render of height and width values on the UI (height =windows.innerHeight & width = windows.innerWidth)
despite using useEffect with an empty dependency array.
I've deployed useState
inside useEffect
to update height
and width
. My understanding was that useEffect
gets executed only once(after the initial render) if used with an empty dependency array but on resizing the screen size, height
and width
gets updated as well thereby causing re-render
Upvotes: 2
Views: 61
Reputation: 477
the window.addEventListener
method runs just one time and then you have a listener for resize
and its call back excuted. the window.addEventListener
does'nt execute on each resize, it's callback does, ist it clear?
Upvotes: 0
Reputation: 3579
I think that's because you added addEventListener
for resizing window in useEffect
, So whenever window in resized it's callback function will be called and your states will be changed so your component will be re-rendered
Upvotes: 0
Reputation: 1930
The useEffect
is called only once, but since you have added a listener on the window object using addEventListener
. The code inside the handler (which sets the state) gets executed, whenever there window size is changed. This state update will cause your component to re-render and update the UI
Upvotes: 0
Reputation: 1099
Upvotes: 1