This solution will work for your use case.
So we have 2 useEffect
hooks.
The first useEffect
attached an event listener to the window
object. Because the window
is used in a useEffect
hook, it won't be executed on the server-side.
The second useEffect
hook will listen to the state changes on innerWidth
, which is being updated whenever the resize
event happens.
const [innerWidth, setInnerWidth] = useState<number | undefined>();
useEffect(() => {
// Handler to call on window resize
function handleResize() {
setInnerWidth(window.innerWidth);
}
// Add event listener
window.addEventListener('resize', handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
return () => window.removeEventListener('resize', handleResize);
}, []);
useEffect(() => {
// Handle your changes
console.log(innerWidth);
}, [innerWidth]);
Inspired by this useWindowResize implementation