Count Up

zosasounds

19,431Toliv Social users
$120kraised for Toliv
14,300TikTok followers
662commits
"use client";

import { useEffect, useRef, useState } from "react";

/**
 * Count Up: a number that runs from `from` to `to` the first time it scrolls
 * into view, easing out so it lands softly. The stats on zosasounds.com.
 *
 *   <CountUp to={19378} />
 *   <CountUp to={120} prefix="$" suffix="k" />
 *
 * The final number is in the HTML from the start, so crawlers, screen readers
 * and anyone with reduced motion get it straight away. Change `replayKey` to
 * run it again.
 */
export type CountUpProps = {
  to: number;
  from?: number;
  duration?: number;
  prefix?: string;
  suffix?: string;
  locale?: string;
  replayKey?: string | number;
  className?: string;
  style?: React.CSSProperties;
};

const easeOutCubic = (p: number) => 1 - Math.pow(1 - p, 3);

export function CountUp({
  to,
  from = 0,
  duration = 1400,
  prefix = "",
  suffix = "",
  locale = "en-US",
  replayKey,
  className,
  style,
}: CountUpProps) {
  const el = useRef<HTMLSpanElement>(null);
  const [value, setValue] = useState(to);

  useEffect(() => {
    const node = el.current;
    if (!node || matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    let raf = 0;
    const run = () => {
      let t0: number | null = null;
      const step = (ts: number) => {
        if (t0 === null) t0 = ts;
        const p = Math.min(1, (ts - t0) / duration);
        setValue(Math.round(from + (to - from) * easeOutCubic(p)));
        if (p < 1) raf = requestAnimationFrame(step);
      };
      raf = requestAnimationFrame(step);
    };
    const io = new IntersectionObserver(
      ([e]) => {
        if (!e.isIntersecting) return;
        io.disconnect();
        run();
      },
      { threshold: 0.5 },
    );
    io.observe(node);
    return () => {
      io.disconnect();
      cancelAnimationFrame(raf);
    };
  }, [to, from, duration, replayKey]);

  return (
    <span ref={el} className={className} style={{ fontVariantNumeric: "tabular-nums", ...style }}>
      {prefix}
      {new Intl.NumberFormat(locale).format(value)}
      {suffix}
    </span>
  );
}