BACK
Use casesScroll direction — sticky header
Use cases · 54

Scroll direction — sticky header

Pattern

A sticky header in mobile apps: scroll down and the header hides to give the content room. Scroll up and it comes back. We need a "scroll direction" stream, not a stream of coordinates.

The problem it solves

Every scroll event is hundreds of pixel deltas a second. Reacting to each one means dizziness and lag. Imperative prevY/currentY variables get duplicated across components and easily fall out of sync.

Operators and why they matter

  • throttleTime — cut the scroll-event rate down.
  • pairwise — gives the pair [previous, current] position without an external variable.
  • map(([prev, curr]) => curr > prev ? 'down' : 'up') — turn the difference into a direction.
  • distinctUntilChanged — pass on only a direction change.

Gotchas

  • debounceTime instead of throttle — the direction updates only after scrolling stops. The header "lags behind".
  • Without distinctUntilChanged the header gets a hundred identical "down"s in a row and change detection chokes.
  • Don't forget the initial position (0), or the first scroll event has nothing to compare with.

What you get

The header gets only meaningful "direction changed" events, not a stream of pixels.

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