JAVASCRIPT
React useWindowSize Hook for Responsive UI Components
Build a React useWindowSize custom hook to efficiently track and respond to changes in the browser window's dimensions, ideal for responsive design.
import { useState, useEffect } from 'react';
function useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
useEffect(() => {
function handleResize() {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
// Set initial size immediately on mount
handleResize();
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []); // Empty array ensures that effect is only run on mount and unmount
return windowSize;
}
// Usage example:
// function MyComponent() {
// const { width, height } = useWindowSize();
//
// return (
// <div>
// <p>Window Width: {width}px</p>
// <p>Window Height: {height}px</p>
// {width && width < 768 && <p>This is a small screen!</p>}
// </div>
// );
// }
How it works: The `useWindowSize` hook provides the current width and height of the browser window. It initializes state with `undefined` to handle server-side rendering. `useEffect` adds a `resize` event listener to the window, updating the state whenever the window dimensions change. It also cleans up the event listener on component unmount, preventing memory leaks.