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?
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