Scrolling up · bottom of page in view: no

All hooks / Viewport and media

useScrollDirection

190 B minified and brotliedSourceMarkdown✓ Works in all modern browsers

The direction the page last scrolled: 'up' or 'down'.

Re-renders only when the direction flips, not on every scroll event. Movements smaller than threshold pixels are ignored, so small jitters (trackpad bounce, iOS overscroll) don't flip it. Always 'up' at the top of the page, on the server, and during hydration.

Import

import { useScrollDirection } from '@vincent.ri/react-tils'
// or only this hook
import { useScrollDirection } from '@vincent.ri/react-tils/useScrollDirection'

Usage

const direction = useScrollDirection()
return <header className={direction === 'down' ? 'header hidden' : 'header'}>…</header>

Live demo

Scroll down, then up. Also shown in the status bar.

scrolling up

When to use it

Hiding a header while scrolling down and showing it when scrolling up, or showing a "back to top" button only while scrolling up.

When not to

You need the position itself; use useWindowScroll. For a header that just sticks, use CSS position: sticky.

API

function useScrollDirection(threshold?: number): ScrollDirection
ParameterDescription
thresholdIgnore movements smaller than this, in pixels. Default 10.

Types

export type ScrollDirection = "up" | "down";

Browser support

Uses only long-established browser features, so it works wherever React does.

First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).