Number Ticker
An animated number counter for React and Tailwind CSS that springs up or down to its value when it scrolls into view. Formatting uses Intl.NumberFormat (locales, currency, percent, decimals), digits are tabular so nothing jitters, and the final value is rendered on the server for SEO.
- Server-rendered final value
- Intl.NumberFormat
- Spring physics
- Counts up & down
- No re-renders
- prefers-reduced-motion
- GitHub stars
- 12,480+
- Uptime
- 99.98%
- Monthly revenue
- $48,200
import { NumberTicker } from "@/components/dusk/text/number-ticker";
const stats = [
{ label: "GitHub stars", ticker: <NumberTicker value={12480} suffix="+" /> },
{ label: "Uptime", ticker: <NumberTicker value={99.98} suffix="%" from={90} /> },
{ label: "Monthly revenue", ticker: <NumberTicker value={48200} currency="USD" decimals={0} /> },
];
export default function NumberTickerDemo() {
return (
<dl className="grid w-full max-w-2xl gap-6 text-center sm:grid-cols-3">
{stats.map((stat) => (
<div
key={stat.label}
className="flex flex-col-reverse gap-1 rounded-xl border border-white/10 bg-white/[0.03] px-4 py-6"
>
<dt className="text-sm text-white/55">{stat.label}</dt>
<dd className="text-4xl font-semibold tracking-tight text-white">{stat.ticker}</dd>
</div>
))}
</dl>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/number-ticker.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/text/number-ticker.tsx.number-ticker.tsx "use client"; import * as React from "react"; import { animate, useInView, useMotionValue, useMotionValueEvent, useReducedMotion, } from "motion/react"; import { cn } from "@/lib/utils"; type NumberTickerTag = "span" | "p" | "div" | "strong" | "data" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6"; export interface NumberTickerProps extends Omit<React.HTMLAttributes<HTMLElement>, "children" | "prefix"> { /** The number to count to. Changing it later springs from the current value to the new one. */ value: number; /** Where the count starts the first time it comes into view. */ from?: number; /** BCP 47 locale for `Intl.NumberFormat`. Fixed by default so server and browser render the same string. */ locale?: string; /** ISO 4217 code, e.g. `"USD"`. Formats as currency. */ currency?: string; /** Fixed number of decimals. Defaults to the decimals in `value` (or the currency's default). */ decimals?: number; /** Any other `Intl.NumberFormat` options (`notation`, `style: "percent"`, `signDisplay`…). They win over the props above. */ format?: Intl.NumberFormatOptions; /** Text before the number, e.g. `"~"`. */ prefix?: string; /** Text after the number, e.g. `"+"` or `" users"`. */ suffix?: string; /** Spring duration in seconds (the perceived length of the count). */ duration?: number; /** Spring bounciness, 0–1. Keep at 0 to never overshoot the target. */ bounce?: number; /** Seconds to wait after entering the view. */ delay?: number; /** Count only the first time it scrolls into view. When `false` it recounts from `from` every time. */ once?: boolean; /** Set to `false` to always show the final value. */ animate?: boolean; /** Element to render. */ as?: NumberTickerTag; } /** Number of decimal places in a plain number, e.g. 4.25 → 2. */ function decimalPlaces(n: number) { if (!Number.isFinite(n)) return 0; const [, fraction = ""] = String(n).split("."); return Math.min(fraction.replace(/e.*$/, "").length, 6); } /** * A number that counts up (or down) to its value with a spring when it * scrolls into view, formatted with `Intl.NumberFormat`. * * The final value is rendered on the server, so search engines, no-JS * visitors and screen readers always get the real number (the animated copy * is `aria-hidden`; a visually hidden copy holds the final value). Digits use * `tabular-nums` and the element reserves the width of its widest value, so * nothing around it jitters. Under reduced motion the final value is shown. */ export function NumberTicker({ value, from = 0, locale = "en-US", currency, decimals, format, prefix = "", suffix = "", duration = 1.6, bounce = 0, delay = 0, once = true, animate: shouldAnimate = true, as = "span", className, ...props }: NumberTickerProps) { const Comp = as as React.ElementType; const rootRef = React.useRef<HTMLElement>(null); const liveRef = React.useRef<HTMLSpanElement>(null); const primed = React.useRef(false); const played = React.useRef(false); const reduceMotion = useReducedMotion(); const inView = useInView(rootRef, { once, amount: 0.5 }); const motionValue = useMotionValue(value); // Options are compared by content so inline objects don't rebuild the formatter every render. const formatKey = JSON.stringify(format ?? null); const formatter = React.useMemo(() => { const extra = JSON.parse(formatKey) as Intl.NumberFormatOptions | null; const options: Intl.NumberFormatOptions = currency ? { style: "currency", currency } : {}; const fixed = decimals ?? (!currency && (extra?.style ?? "decimal") === "decimal" && extra?.minimumFractionDigits == null && extra?.maximumFractionDigits == null && extra?.notation == null ? decimalPlaces(value) : undefined); if (fixed != null) { options.minimumFractionDigits = fixed; options.maximumFractionDigits = fixed; } const nf = new Intl.NumberFormat(locale, { ...options, ...extra }); const digits = nf.resolvedOptions().maximumFractionDigits ?? 0; const step = 0.5 * 10 ** -digits; // Snap values that would round to zero so a count never shows "-0". return (n: number) => `${prefix}${nf.format(Math.abs(n) < step ? 0 : n)}${suffix}`; }, [locale, currency, decimals, formatKey, value, prefix, suffix]); // Write the animated number straight to the DOM: no React render per frame. useMotionValueEvent(motionValue, "change", (latest) => { if (liveRef.current) liveRef.current.textContent = formatter(latest); }); const enabled = shouldAnimate && !reduceMotion; // Before the first client paint, rewind to `from` so the count can play when it's seen. React.useLayoutEffect(() => { if (!enabled || primed.current) return; primed.current = true; motionValue.jump(from); }, [enabled, from, motionValue]); // React re-renders the final string; keep the DOM showing the motion value instead. React.useLayoutEffect(() => { if (liveRef.current) liveRef.current.textContent = formatter(motionValue.get()); }); React.useEffect(() => { if (!enabled) { motionValue.jump(value); return; } if (!inView) { if (!once && played.current) motionValue.jump(from); return; } played.current = true; const controls = animate(motionValue, value, { type: "spring", duration, bounce, delay }); return () => controls.stop(); }, [enabled, inView, once, value, from, duration, bounce, delay, motionValue]); const finalText = formatter(value); const fromText = formatter(from); const stack = "[grid-area:1/1] whitespace-nowrap"; return ( <Comp ref={rootRef} data-slot="number-ticker" {...(as === "data" ? { value: String(value) } : null)} className={cn("inline-grid justify-items-end tabular-nums", className)} {...props} > {/* The real value for screen readers and search engines. */} <span className="sr-only">{finalText}</span> {/* Invisible copies reserve the widest of the start and end values. */} <span aria-hidden className={cn(stack, "invisible select-none")}> {finalText} </span> <span aria-hidden className={cn(stack, "invisible select-none")}> {fromText} </span> <span ref={liveRef} aria-hidden className={stack}> {finalText} </span> </Comp> ); }
Usage
import { NumberTicker } from "@/components/dusk/text/number-ticker"
export function Stats() {
return (
<p className="text-4xl font-bold">
<NumberTicker value={48200} currency="USD" decimals={0} />
</p>
)
}Examples
Locales & formats
Pass a locale, a currency, fixed decimals or any Intl.NumberFormat options through format. Set from above value to count down.
de-DE · EUR1.234.567,89 €
en-IN · grouping1,25,00,000
ja-JP · JPY¥98,000
percent87.3%
countdown0s left
import { NumberTicker } from "@/components/dusk/text/number-ticker";
export default function NumberTickerFormatsDemo() {
return (
<div className="grid w-full max-w-lg gap-3 font-medium">
<Row label="de-DE · EUR">
<NumberTicker value={1234567.89} locale="de-DE" currency="EUR" />
</Row>
<Row label="en-IN · grouping">
<NumberTicker value={12500000} locale="en-IN" />
</Row>
<Row label="ja-JP · JPY">
<NumberTicker value={98000} locale="ja-JP" currency="JPY" />
</Row>
<Row label="percent">
<NumberTicker value={0.873} format={{ style: "percent", maximumFractionDigits: 1 }} />
</Row>
<Row label="countdown">
<NumberTicker value={0} from={100} suffix="s left" duration={2.4} />
</Row>
</div>
);
}
function Row({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="flex items-baseline justify-between gap-4 border-b border-white/10 pb-3 last:border-0">
<span className="text-sm text-white/50">{label}</span>
<span className="text-2xl">{children}</span>
</div>
);
}Live values
When value changes, the number springs from where it is to the new value, up or down. A little bounce makes updates feel physical.
Cart total · 3 items
$74.97
"use client";
import * as React from "react";
import { Minus, Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { NumberTicker } from "@/components/dusk/text/number-ticker";
const PRICE = 24.99;
export default function NumberTickerLiveDemo() {
const [items, setItems] = React.useState(3);
return (
<div className="w-full max-w-xs rounded-xl border border-white/10 bg-white/[0.03] p-5">
<p className="text-sm text-white/55">Cart total · {items} items</p>
<NumberTicker
as="p"
value={items * PRICE}
currency="USD"
duration={0.8}
bounce={0.15}
className="mt-1 text-4xl font-bold tracking-tight"
/>
<div className="mt-4 flex gap-2">
<Button
variant="outline"
size="icon-sm"
aria-label="Remove item"
onClick={() => setItems((n) => Math.max(0, n - 1))}
>
<Minus />
</Button>
<Button size="sm" onClick={() => setItems((n) => n + 1)}>
<Plus /> Add item
</Button>
</div>
</div>
);
}API Reference
Also accepts any HTML attribute for the rendered element.
| Prop | Type | Default | Description |
|---|---|---|---|
| value | number | — | The number to count to. Changing it springs from the current value. |
| from | number | 0 | Where the count starts the first time it comes into view. |
| locale | string | "en-US" | Locale for Intl.NumberFormat. Fixed by default so server and browser output match. |
| currency | string | — | ISO 4217 code such as "USD". Formats as currency. |
| decimals | number | — | Fixed decimal places. Defaults to the decimals in value (or the currency's default). |
| format | Intl.NumberFormatOptions | — | Any other formatter options (notation, style, signDisplay…). They win over the props above. |
| prefix | string | — | Text before the number. |
| suffix | string | — | Text after the number, e.g. "+" or "%". |
| duration | number | 1.6 | Spring duration in seconds. |
| bounce | number | 0 | Spring bounciness (0–1). 0 never overshoots the target. |
| delay | number | 0 | Seconds to wait after entering the view. |
| once | boolean | true | Count only the first time. When false it recounts on every entry. |
| animate | boolean | true | Set to false to always show the final value. |
| as | "span" | "p" | "div" | "strong" | "data" | "h1" … "h6" | "span" | Element to render. "data" also sets its machine-readable value attribute. |
Accessibility
- The final, formatted value is rendered on the server, so crawlers and no-JS visitors see the real number, not 0.
- Screen readers read the final value from a visually hidden copy; the animating digits are aria-hidden, so nothing is announced mid-count.
- tabular-nums and a reserved width (the wider of the start and end values) prevent layout shift while counting.
- The count runs outside React (Motion value written to the DOM), so it never re-renders your page.
- With prefers-reduced-motion the final value is shown immediately.