window resize next js
Using Next.js to Handle Window Resize Events
- Import the
useEffect
anduseState
hooks from React.
import { useEffect, useState } from 'react';
- Define a state variable to hold the window width.
const [windowWidth, setWindowWidth] = useState(typeof window !== 'undefined' ? window.innerWidth : 0);
- Create an event listener for the window resize event.
useEffect(() => {
const handleResize = () => {
setWindowWidth(window.innerWidth);
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
- Use the
windowWidth
state variable in your component.
return (
<div>
Window width: {windowWidth}
</div>
);