JAVASCRIPT
React useWindowSize Hook to Track Browser Dimensions
Get real-time updates on the browser window's width and height in your React components, ideal for responsive UI adjustments.
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 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;
}
How it works: The `useWindowSize` hook provides the current width and height of the browser window. It initializes its state with the current dimensions and then adds an event listener for the `resize` event. Whenever the window dimensions change, the state is updated, causing any consuming components to re-render with the new sizes. This is highly useful for creating layouts that adapt to the available screen space.