In Next.js, you can use the useEffect
hook along with the window
object to handle window resizing events. Here's a simple example of how you can implement a custom hook for handling window resizing events in Next.js:
jsx// useWindowSize.js
import { useState, useEffect } from 'react';
const useWindowSize = () => {
const [windowSize, setWindowSize] = useState({
width: typeof window !== 'undefined' ? window.innerWidth : 0,
height: typeof window !== 'undefined' ? window.innerHeight : 0,
});
useEffect(() => {
const handleResize = () => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
};
// Add event listener to window resize
window.addEventListener('resize', handleResize);
// Initial call to set initial window size
handleResize();
// Clean up the event listener when the component unmounts
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return windowSize;
};
export default useWindowSize;
Now, you can use this custom hook in your Next.js components:
jsx// YourComponent.js
import React from 'react';
import useWindowSize from '../path/to/useWindowSize';
const YourComponent = () => {
const windowSize = useWindowSize();
return (
<div>
<p>Window Width: {windowSize.width}</p>
<p>Window Height: {windowSize.height}</p>
{/* Your component content */}
</div>
);
};
export default YourComponent;
This useWindowSize
custom hook will handle window resizing events and provide the current window width and height in your components. The event listener is set up when the component mounts and removed when the component unmounts, ensuring that you clean up any unnecessary resources.