JAVASCRIPT
Track Browser Window Size with a `useWindowSize` React Hook
Create a `useWindowSize` React hook to dynamically get and respond to changes in the browser window's dimensions, perfect for responsive component rendering.
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(); // Set initial size
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowSize;
}
// Example Usage:
// function ResponsiveComponent() {
// const { width, height } = useWindowSize();
// if (width < 768) {
// return <p>Small Screen View ({width}px)</p>;
// } else {
// return <p>Large Screen View ({width}px)</p>;
// }
// }
How it works: The `useWindowSize` hook efficiently tracks and provides the current width and height of the browser window. It sets up an event listener for `resize` events and updates its state, ensuring your components can react dynamically to changes in screen dimensions, which is essential for building adaptive and responsive user interfaces.