Track window width and height with updates on resize. SSR-safe with optional debounce.
import { useState, useEffect } from 'react';
export function useWindowSize(): { width: number; height: number } {
const [size, setSize] = useState(() =>
typeof window !== 'undefined'
? { width: window.innerWidth, height: window.innerHeight }
: { width: 0, height: 0 }
);
useEffect(() => {
const update = () =>
setSize({ width: window.innerWidth, height: window.innerHeight });
update();
window.addEventListener('resize', update);
return () => window.removeEventListener('resize', update);
}, []);
return size;
}Returns { width, height } of the window. Updates on resize. On SSR returns { width: 0, height: 0 } then hydrates.
Use for responsive logic or chart dimensions.
const { width, height } = useWindowSize();