JAVASCRIPT
Track Browser Window Dimensions with useWindowSize React Hook
Develop a custom React hook to efficiently get and update the current browser window width and height, enabling responsive layouts and dynamic UI adjustments.
import { useState, useEffect } from 'react';
function useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: typeof window !== 'undefined' ? window.innerWidth : 0,
height: typeof window !== 'undefined' ? window.innerHeight : 0,
});
useEffect(() => {
if (typeof window === 'undefined') return; // Exit if window is not available (e.g., SSR)
const handleResize = () => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
};
window.addEventListener('resize', handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
return () => window.removeEventListener('resize', handleResize);
}, []); // Empty array ensures that effect is only run on mount and unmount
return windowSize;
}
// How to use it:
// function ResizableBox() {
// const { width, height } = useWindowSize();
// return (
// <div style={{ padding: '20px', border: '1px solid black' }}>
// <p>Window Width: {width}px</p>
// <p>Window Height: {height}px</p>
// <p>Resize your browser window to see changes!</p>
// </div>
// );
// }
How it works: The `useWindowSize` hook provides real-time access to the browser window's dimensions. It uses `useState` to store the current `width` and `height`, initialized with `window.innerWidth` and `window.innerHeight`. An `useEffect` hook is used to add and remove a `resize` event listener on the `window` object. The `handleResize` function updates the state whenever the window is resized, causing components that use this hook to re-render with the latest dimensions. The effect runs only once on mount and cleans up on unmount, ensuring efficient event listener management.