BACK
Use casesResize breakpoint — responsive stream
Use cases · 53

Resize breakpoint — responsive stream

Pattern

Window resize emits dozens of events a second — every pixel. But the UI only cares about a category change: mobile / tablet / desktop. Turn the pixel stream into a stream of breakpoints.

The problem it solves

If every pixel-resize triggers Change Detection, the UI lags. If you store the breakpoint in a field and update it in a resize handler, you easily get a stale value or forget the subscription on destroy.

Operators and why they matter

  • startWith(window.innerWidth) — the initial width so the UI knows the state before the first resize.
  • auditTime(20) — emit the latest width once every 20ms. Smooth out the flood of events.
  • map(width => breakpoint(width)) — classify the width into a category.
  • distinctUntilChanged — pass on only a category change, not every width.

Gotchas

  • debounceTime — the UI updates only AFTER the resize ENDS. During a smooth window drag the category updates with a lag.
  • throttleTime without a trailing config — the final width can be lost, and the breakpoint gets stuck.
  • Don't emit pixels to the template if the UI depends only on the category. It's needless noise for change detection.

What you get

The UI reacts only to a meaningful breakpoint change, not to every resize pixel.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...