Skip to content Skip to sidebar Skip to footer

React Hooks Useeffect Update Window.innerheight

I want to update state with the inner window height as I resize the screen. When I log the state height within the useEffect hook I get 0 each time however, when I log inside the u

Solution 1:

Your useEffect is only being run one time, when the component mounts (because of the empty array [] you passed as the second argument)

If you simply log outside of it, you'll see your state value is being updated correctly

const [height, setHeight] = useState(0);

  useEffect(() => {
    constupdateWindowDimensions = () => {
      const newHeight = window.innerHeight;
      setHeight(newHeight);
      console.log("updating height");
    };

    window.addEventListener("resize", updateWindowDimensions);

    return() =>window.removeEventListener("resize", updateWindowDimensions) 

  }, []);

  console.log("give height", height);

Also you should move the declaration of that function inside the useEffect so it's not redeclared on every render

Post a Comment for "React Hooks Useeffect Update Window.innerheight"