react hooks useEffect update window.innerHeight

Viewed 10336

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);
 }, []);
3 Answers

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

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.

I know this is too late for answer, but we can define a hook for this purpose. In here you can find a custom hook that update width and height of window on every resize.

Related