GooseUI

Components

useScrollThreshold

New

useScrollThreshold tells you whether the page has been scrolled past a threshold. It turns on and off at different offsets, so a sticky header that shrinks on scroll does not flicker when the user stops right at the boundary.

Preview

The header turns compact below 80px and goes back only above 32px. Stop between the two marks and nothing jumps.

scrollTop: 0compact: false
off below 32px going upon past 80px going down
Acme Store

Scroll this box slowly back and forth around 32–80px

Installation

npx shadcn@latest add @gooseui/use-scroll-threshold
pnpm dlx shadcn@latest add @gooseui/use-scroll-threshold
yarn dlx shadcn@latest add @gooseui/use-scroll-threshold
bunx --bun shadcn@latest add @gooseui/use-scroll-threshold

Usage

import { useScrollThreshold } from "@/hooks/use-scroll-threshold"

export function SiteHeader() {
  const compact = useScrollThreshold(80)

  return (
    <header
      data-compact={compact}
      className="sticky top-0 h-16 transition-all data-[compact=true]:h-12 data-[compact=true]:shadow"
    >
      <Logo />
    </header>
  )
}

Examples

Custom release point

By default the flag turns off at half the threshold. Set releaseAt when the header changes height a lot and you need a wider gap.

// on after 200px, off only above 60px
const pastHero = useScrollThreshold(200, { releaseAt: 60 })

Scroll container

Pass a ref to watch an element with its own scroll instead of the window, as in the preview.

function Panel() {
  const container = useRef<HTMLDivElement>(null)
  const compact = useScrollThreshold(80, { releaseAt: 32, container })

  return (
    <div ref={container} className="h-96 overflow-y-auto">
      <PanelHeader compact={compact} />
      <PanelBody />
    </div>
  )
}

Show a back-to-top button

The same flag works for anything that appears after some scrolling.

const visible = useScrollThreshold(600)

return visible ? <ScrollToTopButton /> : null

Parameters

NameTypeDefaultDescription
thresholdnumber64Offset in px past which the flag turns on while scrolling down
options.releaseAtnumberthreshold / 2Offset in px below which the flag turns off. Never higher than threshold
options.containerRefObject<HTMLElement | null>-Element to watch instead of the window

Returns

NameTypeDescription
passedbooleantrue while the scroll position is past the threshold

Features

  • Hysteresis. Two boundaries instead of one, so the state does not flip back and forth at the edge
  • Passive listener. The scroll handler never blocks scrolling
  • One read per frame. Updates go through requestAnimationFrame and re-render only when the flag changes