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
Answers
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
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.