Skip to content

useThreshold

Latched threshold crossings with hysteresis.

A React hook that watches a numeric value (scroll, drag, progress) and latches which named thresholds it has crossed. Supports hysteresis dead zones and per-threshold onCross callbacks.

Installation

pnpm dlx shadcn@latest add @frontal-labs/use-threshold

Usage

import { useThreshold } from "@/hooks/use-threshold";
 
function ScrollHeader({ scrollY }: { scrollY: number }) {
  const { crossed } = useThreshold(scrollY, [
    { id: "compact", at: 80, hysteresis: 8 },
    { id: "solid", at: 200, hysteresis: 16 },
  ]);
 
  return <header data-compact={crossed.compact} data-solid={crossed.solid} />;
}

Callbacks on crossing

const { lastCrossedId } = useThreshold(progress, [
  {
    id: "complete",
    at: 100,
    onCross: (direction) => direction === "up" && celebrate(),
  },
]);

Thresholds added later are seeded from the current value, so they never fire on the commit they appear — only on subsequent moves that clear their edge.

API

function useThreshold(
  value: number,
  thresholds: readonly {
    id: string;
    at: number;
    hysteresis?: number;
    onCross?: (direction: "up" | "down") => void;
  }[],
): { crossed: Record<string, boolean>; lastCrossedId: string | null };

Parameters

Return value