JAVASCRIPT
Custom useWindowSize Hook for Responsive Layouts
Build a custom React hook, useWindowSize, to track the real-time width and height of the browser window, enabling dynamic responsive components and layouts.
import React, { useState, useEffect } from 'react';
function useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: typeof window !== 'undefined' ? window.innerWidth : 0,
height: typeof window !== 'undefined' ? window.innerHeight : 0,
});
useEffect(() => {
// Only run on client-side
if (typeof window === 'undefined') {
return;
}
function handleResize() {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
window.addEventListener('resize', handleResize);
// Call handler once to set initial size
handleResize();
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 < 768 ? (
<p>This is a mobile view.</p>
) : (
<p>This is a desktop view.</p>
)}
</div>
);
}
How it works: The `useWindowSize` hook tracks and provides the current width and height of the browser window. It initializes state with `window.innerWidth` and `window.innerHeight` (with SSR-safe checks). An `useEffect` hook adds and removes a `resize` event listener, updating the state whenever the window dimensions change. This is useful for creating responsive components that adapt their behavior or rendering based on the viewport size, without directly manipulating the DOM.