JAVASCRIPT
Track and Access Browser Window Dimensions
A custom React hook to get and react to changes in the browser window's `width` and `height`, useful for creating responsive UI components.
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;
}
// Example Usage:
// function ResponsiveComponent() {
// 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 mobile view!</p>
// ) : (
// <p>This is a desktop view!</p>
// )}
// </div>
// );
// }
How it works: This `useWindowSize` hook initializes state with `undefined` dimensions, then uses `useEffect` to add and remove a `resize` event listener to the window. The `handleResize` function updates the state with the current `innerWidth` and `innerHeight`. The initial call to `handleResize` sets the dimensions on mount, and the cleanup function ensures the listener is removed on unmount, preventing memory leaks.