useBreakpointLoading saved progress…

useBreakpoint

Build a hook that reports which responsive breakpoint the viewport is currently in. Layout code often needs to branch on screen size — render a sidebar at desktop widths, a hamburger menu at phone widths — and hard-coding window.innerWidth < 768 in a dozen places is brittle. useBreakpoint() reads the current window width, maps it to a named band, and re-reports whenever the window resizes, so a component can simply read a name like 'lg' and re-render when the viewport crosses a threshold.

Signature

function useBreakpoint(): 'sm' | 'md' | 'lg' | 'xl';

The hook takes no arguments and returns the active breakpoint name. The thresholds are fixed (Tailwind-like):

  • width < 640'sm'
  • width >= 640 and < 768'md'
  • width >= 768 and < 1024'lg'
  • width >= 1024'xl'

Examples

function Layout() {
  const breakpoint = useBreakpoint();

  // At 'sm'/'md' show a compact menu; at 'lg'/'xl' show the full sidebar.
  return breakpoint === 'sm' || breakpoint === 'md' ? <MobileNav /> : <Sidebar />;
}
// width 500  -> 'sm'
// width 640  -> 'md'   (the lower edge of md is inclusive)
// width 767  -> 'md'
// width 768  -> 'lg'
// width 1024 -> 'xl'
// Resizing from 500 to 900 must change the returned name from 'sm' to 'lg'.

Notes

  • Boundaries are inclusive on the lower edge. A width of exactly 640 is 'md', 768 is 'lg', and 1024 is 'xl'. 639 is still 'sm'.
  • It must update on resize. Reading the width once is not enough; when the window crosses a threshold the returned name has to change, which means subscribing to the resize event.
  • Clean up on unmount. Remove the resize listener when the component unmounts, or it leaks and keeps firing into a component that no longer exists.
  • Seed from the current width. The first value the hook returns must already reflect window.innerWidth at mount, not a placeholder you correct after the first resize.
  • Stay in one band per render. Every render returns exactly one of 'sm', 'md', 'lg', 'xl' — never undefined or an in-between value.
Loading editor…