Window size hook with a selector to skip needless re-renders
Many components care about the size of the browser window, but most of them only need one fact derived from it: is the window in portrait orientation, how many columns fit, is there room for a sidebar. If every one of those components re-rendered on every resize event, dragging the window edge would re-render the whole page dozens of times per second. Implement a React hook, useViewportSize, that reads the window size and lets the caller select only the part it cares about.
type ViewportSize = { width: number; height: number };
function useViewportSize(): ViewportSize
function useViewportSize<T>(selector: (size: ViewportSize) => T): T
The size is { width: window.innerWidth, height: window.innerHeight }.
selector(size).resize events on window. Re-render the component only when the returned value changes (compared with Object.is). A resize that keeps the selected value the same must not re-render the component.resize listener per mounted component, and remove it when the component unmounts.// window is 1280 x 720
useViewportSize(); // { width: 1280, height: 720 }
useViewportSize((s) => s.width); // 1280
useViewportSize((s) => (s.width >= s.height ? 'landscape' : 'portrait')); // 'landscape'
function PhotoViewer({ photo }) {
// Re-renders only when the orientation flips, not on every pixel of a resize.
const orientation = useViewportSize((s) => (s.width >= s.height ? 'landscape' : 'portrait'));
return <Photo src={photo} fit={orientation === 'landscape' ? 'height' : 'width'} />;
}
// The user resizes 1280 x 720 -> 1100 x 700: still 'landscape', no re-render.
// The user resizes to 700 x 900: 'portrait', PhotoViewer re-renders once.
function SidebarLayout({ minWidth }) {
// The selector reads a prop: when minWidth changes, the result updates in that render.
const showSidebar = useViewportSize((s) => s.width >= minWidth);
return showSidebar ? <WithSidebar /> : <Stacked />;
}
window.innerWidth and window.innerHeight and dispatch resize events on window inside ReactDOM.flushSync. They count the active resize listeners on window.Object.assign(window, { useViewportSize }); below “Do not edit below this line”. The tests use it to call your hook.