Number ticker

Counts a number up (or down) from a start value to its target when it scrolls into view, using IntersectionObserver and requestAnimationFrame. Formats every frame with Intl.NumberFormat (currency, percent, compact, decimals, any locale), keeps width steady with tabular figures, gives screen readers the final value, and shows it straight away when reduced motion is on.

Animation & motionComponentTailwind v4

Source

"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { cn } from "@/lib/utils";

export type NumberTickerProps = {
  /** The number to land on. */
  value: number;
  /** Where the count starts. Defaults to 0. */
  from?: number;
  /** Length of the count in milliseconds. */
  duration?: number;
  /** Wait this long after the element enters the view, in milliseconds. */
  delay?: number;
  /** BCP 47 locale for Intl.NumberFormat. Defaults to the visitor's locale. */
  locale?: string;
  /** Any Intl.NumberFormat options: currency, percent, compact notation, fraction digits. */
  format?: Intl.NumberFormatOptions;
  /** Start when scrolled into view (default) or as soon as it mounts. */
  startOnView?: boolean;
  /** Share of the element that must be visible before it starts, 0 to 1. */
  threshold?: number;
  className?: string;
};

// Fast start, gentle landing: the last digits settle instead of spinning.
const easeOutExpo = (t: number) => (t >= 1 ? 1 : 1 - Math.pow(2, -10 * t));

function prefersReducedMotion() {
  return typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
}

export function NumberTicker({
  value,
  from = 0,
  duration = 1600,
  delay = 0,
  locale,
  format,
  startOnView = true,
  threshold = 0.4,
  className,
}: NumberTickerProps) {
  const ref = useRef<HTMLSpanElement>(null);
  const [current, setCurrent] = useState(from);
  const formatKey = JSON.stringify(format ?? {});
  const formatter = useMemo(() => {
    // Plain numbers keep the target's own decimals, so 1284 never flickers through 1,283.917 on the way up.
    const plain = (format?.style ?? "decimal") === "decimal" && format?.notation !== "compact"
      && format?.minimumFractionDigits === undefined && format?.maximumFractionDigits === undefined
      && format?.maximumSignificantDigits === undefined;
    const decimals = Math.min(String(value).split(".")[1]?.length ?? 0, 20);
    return new Intl.NumberFormat(locale, plain ? { ...format, minimumFractionDigits: decimals, maximumFractionDigits: decimals } : format);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [locale, formatKey, value]);

  useEffect(() => {
    const node = ref.current;
    if (!node) return;
    if (prefersReducedMotion() || from === value) {
      setCurrent(value);
      return;
    }

    let frame = 0;
    let timer: ReturnType<typeof setTimeout> | undefined;
    let fallback: ReturnType<typeof setTimeout> | undefined;
    const run = () => {
      let start: number | undefined;
      // Frames drive the count; a slow timer keeps it moving where frames are throttled (hidden tabs, headless capture).
      const schedule = () => {
        frame = requestAnimationFrame(step);
        fallback = setTimeout(step, 80);
      };
      const step = () => {
        cancelAnimationFrame(frame);
        clearTimeout(fallback);
        const now = performance.now();
        start ??= now;
        const progress = Math.min((now - start) / duration, 1);
        setCurrent(from + (value - from) * easeOutExpo(progress));
        if (progress < 1) schedule();
      };
      timer = setTimeout(schedule, delay);
    };

    if (!startOnView || typeof IntersectionObserver === "undefined") {
      run();
    } else {
      const observer = new IntersectionObserver(
        ([entry]) => {
          if (!entry?.isIntersecting) return;
          observer.disconnect();
          run();
        },
        { threshold },
      );
      observer.observe(node);
      return () => {
        observer.disconnect();
        clearTimeout(timer);
        clearTimeout(fallback);
        cancelAnimationFrame(frame);
      };
    }
    return () => {
      clearTimeout(timer);
      clearTimeout(fallback);
      cancelAnimationFrame(frame);
    };
  }, [value, from, duration, delay, startOnView, threshold]);

  return (
    <span ref={ref} className={cn("inline-block tabular-nums", className)}>
      <span aria-hidden="true">{formatter.format(current)}</span>
      <span className="sr-only">{formatter.format(value)}</span>
    </span>
  );
}