JAVASCRIPT
Custom React Hook for Dynamic Window Dimensions
A React hook that provides real-time updates for the browser window's width and height. Essential for creating responsive components that adapt to screen size changes.
import { useState, useEffect } from 'react';
function useWindowSize() {
// Initialize state with undefined width/height so server and client match
// Learn more here: https://joshwcomeau.com/react/the-complete-guide-to-useeffect/#right-sizing-our-state
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
useEffect(() => {
// Handler to call on window resize
function handleResize() {
// Set window width/height to state
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
// Add event listener
window.addEventListener('resize', handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
// Remove event listener on cleanup
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>
// Window width: {width}px, Window height: {height}px
// // </div>
// );
// }
How it works: This `useWindowSize` hook tracks and provides the current dimensions of the browser window. It initializes with `undefined` values to handle server-side rendering gracefully. An `useEffect` hook adds a `resize` event listener to the `window` object when the component mounts and removes it on unmount. The `handleResize` function updates the state with the current `innerWidth` and `innerHeight`, making the window dimensions available to any component that uses this hook.