0
import React, { useState, useEffect } from 'react';

const WindowSize = () => {
  // Add your state and useEffect logic here
  const [windowWidth, setWindowWidth] = useState(window.innerWidth);
  const [windowHeight, setWindowHeight] = useState(window.innerHeight);

  const onResize = () => {
    console.log("resize detected");
    const width = window.innerWidth;
    const height = window.innerHeight;
    setWindowWidth(width);
    setWindowHeight(height);
  }
  
  useEffect(() => {
    window.addEventListener('resize', onResize);

    return () => {
      window.removeEventListener('resize', onResize);
    }
  })

  return (
    <div>
      {/* Display the current window size here */}
      <p>Width: {windowWidth}</p>
      <p>Height: {windowHeight}</p>
    </div>
  );
};

export default WindowSize;

In the code above, useEffect only runs once after the initial render. Within it running once, it adds an event listener and then it removes an event listener.

How come then, whenever I change the browser window size, this code will still update the new width and height?

2
  • Is WindowSize still mounted while you are testing this? Are those p tags and div on the screen while you are testing this? Commented Oct 19, 2023 at 12:58
  • "useEffect only runs once after the initial render", that would be true if the effect had an empty dependency array, but with no dependency array, the effect will run on every render. Commented Oct 19, 2023 at 12:58

2 Answers 2

1

Here for the useEffect there is no dependency array to will be run for every render. And return function will only be called during component unmount

Sign up to request clarification or add additional context in comments.

Comments

0

when clearly the event listener is removed within the same render cycle?

That's incorrect; it is not removed within the same render cycle.

The cleanup function that you return from the effect (return () => { window.removeEventListener('resize', onResize);}) doesn't do anything during the first render. When eventually a second render happen, that's when the cleanup function gets run to teardown the first effect. But immediately after tearing down the first effect, the second effect runs which sets up a new listener. So the first listener sticks around until the second render, then the second listener sticks around until the 3rd render, and so on. Only when the component unmounts will an effect get torn down without setting up a new one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.