react hooks useEffect update window.innerHeight

All we need is an easy explanation of the problem, so here it is.

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 updateWindowDimensions function the height value is updated as expected.

How can I update state with the new value each time?

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

const updateWindowDimensions = () => {
    const newHeight = window.innerHeight;
    setHeight(newHeight);
    console.log('updating height');   
};

 useEffect(() => {
     window.addEventListener('resize', updateWindowDimensions);
     console.log("give height", height);
 }, []);

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 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(() => {
    const updateWindowDimensions = () => {
      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

Method 2

The above Answer by @Galupuf won’t work ideally, until you add updateWindowDimensions call below addEventListener:

window.addEventListener("resize", updateWindowDimensions);
updateWindowDimensions()

Because eventListener won’t run this function until you resize.
so height will remain 0 until you resize.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply