Home > Blockchain >  Forceful Re-render with useEffect
Forceful Re-render with useEffect

Time:11-17

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

CodePudding user response:

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?

CodePudding user response:

  1. you should use const to declare your states
  2. window.addEventListener is declared only once but it will be triggered every resize - so your state will be updated every resize
  3. every time your state change the component will rerender

CodePudding user response:

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

CodePudding user response:

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

  • Related