JAVASCRIPT
React useWindowSize Hook for Responsive Layouts
Access and react to real-time window dimensions in React components with `useWindowSize`, facilitating dynamic and 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,
});
}
window.addEventListener('resize', handleResize);
handleResize(); // Call once to set initial size
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, updating dynamically when the window is resized. This hook is incredibly useful for building responsive user interfaces, conditionally rendering components based on screen size, or adjusting element styles in real-time. It efficiently sets up and tears down an event listener, preventing memory leaks.