Hook returning the active named breakpoint as the window resizes
A design system defines named viewport tiers, each starting at a minimum width. Components need to know which tier is active right now, so they can choose a layout, a page size, or how many columns a grid has. Implement a React hook, useViewportTier, that returns the name of the active tier and updates when the window is resized.
function useViewportTier(tiers: Record<string, number>): string | null
tiers maps each tier name to its minimum width in CSS pixels. All minimum widths are distinct.
window.innerWidth. Minimums are inclusive: at exactly 768px, a tier that starts at 768 is active.null.tiers. { desktop: 1280, phone: 360 } must work.resize events on window, and re-render with the new tier when the width crosses a boundary.tiers argument changes, return the tier for the new configuration without waiting for a resize.const TIERS = { watch: 0, phone: 360, tablet: 768, desktop: 1280 };
// window.innerWidth === 500 -> 'phone'
// window.innerWidth === 768 -> 'tablet' (minimums are inclusive)
// window.innerWidth === 767 -> 'phone'
// window.innerWidth === 2560 -> 'desktop'
useViewportTier({ tablet: 768, desktop: 1280 }); // at 500px -> null
function ProductGrid({ products }) {
const tier = useViewportTier({ phone: 0, tablet: 768, desktop: 1280 });
const columns = { phone: 1, tablet: 2, desktop: 4 }[tier] ?? 1;
return <Grid columns={columns} items={products} />;
}
window.innerWidth and dispatch resize events on window inside ReactDOM.flushSync. They count the active resize listeners on window.Object.assign(window, { useViewportTier }); below “Do not edit below this line”. The tests use it to call your hook.