useWindowSize Hook
Track browser window dimensions with debounced resize handling for responsive component logic.
import { useState, useEffect } from 'react';
export function useWindowSize() {
const [size, setSize] = useState({ width: 0, height: 0 });
useEffect(() => {
let timer: ReturnType<typeof setTimeout>;
const update = () => {
clearTimeout(timer);
timer = setTimeout(() => {
setSize({ width: window.innerWidth, height: window.innerHeight });
}, 150);
};
update();
window.addEventListener('resize', update);
return () => {
window.removeEventListener('resize', update);
clearTimeout(timer);
};
}, []);
return size;
}Use Cases
- Responsive layouts
- Canvas sizing
- Conditional rendering by breakpoint
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
useMediaQuery — Responsive Breakpoint Hook
Subscribe to CSS media query changes and get a boolean flag for responsive rendering logic in React.
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.