Reputation: 569
I'm using this code to listen for resize events in a function component and rerender the component when the window is resized. The problem is, nothing ever gets printed out for either event listener, so I think I have a misunderstanding of how I'm using useEffect here.
const [dimensions, setDimensions] = React.useState({
width: window.innerWidth,
height: window.innerHeight,
});
useEffect(() => {
const handleResize = () => {
console.log(dimensions.width);
setDimensions({
width: window.innerWidth,
height: window.innerHeight,
});
window.addEventListener("load", handleResize, false);
window.addEventListener("resize", handleResize, false);
};
});
Upvotes: 20
Views: 53351
Reputation: 361
const [dimensions, setDimensions] = React.useState({
width: window.innerWidth,
height: window.innerHeight,
});
console.log(dimensions);
const handleResize = () => {
setDimensions({
width: window.innerWidth,
height: window.innerHeight,
});
}
React.useEffect(() => {
window.addEventListener("resize", handleResize, false);
}, []);
Upvotes: 23
Reputation: 825
I found that the event listener on "resize" was not sufficient to populate the window dimensions in the initial load of the page. The following worked for me.
function getWindowDimensions() {
const {innerWidth: width, innerHeight: height} = window;
return {
width,
height
};
}
function useWindowDimensions() {
const defaultDim = {width: null, height: null}
const [windowDimensions, setWindowDimensions] = useState(defaultDim);
useEffect(() => {
setWindowDimensions(getWindowDimensions()) // Necessary to make sure dimensions are set upon initial load
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
}
Upvotes: 0
Reputation: 4515
import { useState, useEffect } from "react";
// Usage
function App() {
const size = useWindowSize();
return (
<div>
{size.width}px / {size.height}px
</div>
);
}
// Hook
function useWindowSize() {
// Initialize state with undefined width/height so server and client renders match
// Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
useEffect(() => {
// Handler to call on window resize
function handleResize() {
// Set window width/height to state
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
// Add event listener
window.addEventListener("resize", handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
// Remove event listener on cleanup
return () => window.removeEventListener("resize", handleResize);
}, []); // Empty array ensures that effect is only run on mount
return windowSize;
}
Upvotes: 37