window resize next js

Using Next.js to Handle Window Resize Events

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