JAVASCRIPT
Tracking Window Dimensions with `useWindowSize`
Build a custom React `useWindowSize` hook to efficiently track and react to changes in the browser window's dimensions for responsive UIs.
import { useState, useEffect } => '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);
// 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;
}
// Example Usage:
// function MyComponent() {
// const { width, height } = useWindowSize();
// return (
// <div>
// <p>Window Width: {width}</p>
// <p>Window Height: {height}</p>
// </div>
// );
// }
How it works: The `useWindowSize` hook provides the current `width` and `height` of the browser window. It attaches a `resize` event listener when the component mounts and cleans it up when the component unmounts, ensuring efficient updates and preventing memory leaks.