# Counting Number

> Smoothly animates from a start value to a target number using a spring or tween. Supports imperative replay via a ref and fires start/complete callbacks.

Docs: https://ui.cnippet.dev/motion/text-animations/counting-number

```tsx
import { CountingNumber } from "@/registry/default/motion/counting-number";

const stats = [
  { label: "Components shipped", suffix: "+", value: 164 },
  { label: "GitHub stars", suffix: "K", value: 4.2 },
  { label: "Monthly downloads", suffix: "K", value: 98 },
  { label: "Contributors", suffix: "", value: 37 },
];

export default function CountingNumberStats() {
  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <div className="grid grid-cols-2 gap-8 sm:grid-cols-4">
        {stats.map((stat) => (
          <div className="text-center" key={stat.label}>
            <p className="font-bold text-4xl text-foreground tracking-tight">
              <CountingNumber
                target={stat.value}
                transition={{ duration: 2, ease: "easeOut", type: "tween" }}
              />
              {stat.suffix}
            </p>
            <p className="mt-1 text-muted-foreground text-xs">{stat.label}</p>
          </div>
        ))}
      </div>
    </div>
  );
}
```

## Installation

**CLI**

```bash
npx shadcn@latest add @cnippet/counting-number
```

**Manual**

1. Install the following dependencies:

```bash
npm install motion
```

2. Copy and paste the following code into your project.

`components/motion/counting-number.tsx`

```tsx
"use client";

import {
  type AnimationPlaybackControls,
  animate,
  motion,
  useMotionValue,
  useReducedMotion,
  useTransform,
  type ValueAnimationTransition,
} from "motion/react";
import {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
} from "react";
import { cn } from "@/lib/utils";

export type CountingNumberRef = {
  startAnimation: () => void;
};

export type CountingNumberProps = {
  from?: number;
  target: number;
  transition?: ValueAnimationTransition;
  className?: string;
  onStart?: () => void;
  onComplete?: () => void;
  autoStart?: boolean;
};

export const CountingNumber = forwardRef<
  CountingNumberRef,
  CountingNumberProps
>(
  (
    {
      from = 0,
      target = 100,
      transition = { duration: 3, ease: "easeInOut", type: "tween" },
      className,
      onStart,
      onComplete,
      autoStart = true,
      ...props
    },
    ref,
  ) => {
    const reduceMotion = useReducedMotion();
    const count = useMotionValue(from);
    const rounded = useTransform(count, (latest) =>
      Math.round(latest).toLocaleString(),
    );
    const controlsRef = useRef<AnimationPlaybackControls | null>(null);

    const startAnimation = useCallback(() => {
      controlsRef.current?.stop();
      onStart?.();
      if (reduceMotion) {
        count.set(target);
        onComplete?.();
        return;
      }
      count.set(from);
      controlsRef.current = animate(count, target, {
        ...transition,
        onComplete: () => onComplete?.(),
      });
    }, [from, target, transition, onStart, onComplete, count, reduceMotion]);

    useImperativeHandle(ref, () => ({ startAnimation }));

    useEffect(() => {
      if (autoStart) startAnimation();
      return () => controlsRef.current?.stop();
    }, [autoStart, startAnimation]);

    return (
      <motion.span className={cn("tabular-nums", className)} {...props}>
        {rounded}
      </motion.span>
    );
  },
);

CountingNumber.displayName = "CountingNumber";
```

3. Update the import paths to match your project setup.

## Usage

```tsx
import { CountingNumber } from "@/components/motion/counting-number";
```

```tsx
<CountingNumber target={1000} />
```

## Anatomy

```tsx
<CountingNumber from={0} target={1000} /> {/* <span> counting from → target */}
```

## Good to know

- It counts from `from` (default `0`) to `target` once, when it mounts.
- Set `autoStart={false}` and call `ref.current.startAnimation()` to start it yourself, for example when it scrolls into view.
- `onStart` and `onComplete` fire at the beginning and end of the count.
- For a number that changes over time, use `AnimatedNumber` or `SlidingNumber`.
- When the user has turned on reduced motion, it shows `target` straight away; `onStart` and `onComplete` still fire.

## Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `target` | `number` | — | The final value to count to |
| `from` | `number` | `0` | Starting value |
| `autoStart` | `boolean` | `true` | Start counting immediately on mount |
| `transition` | `ValueAnimationTransition` | `{ type: "tween", duration: 3, ease: "easeInOut" }` | Motion transition controlling the count animation |
| `onStart` | `() => void` | — | Callback fired when counting starts |
| `onComplete` | `() => void` | — | Callback fired when counting reaches `target` |
| `className` | `string` | — | Class applied to the `<span>` element |

### Ref API

Pass a `ref` to access `startAnimation()` imperatively:

```tsx
const ref = useRef<CountingNumberRef>(null);
ref.current?.startAnimation(); // resets to `from` and counts again
```

## Examples

### Stats Section

Four `CountingNumber` components animate a social-proof grid on mount. Values use `toLocaleString` formatting automatically.

```tsx
import { CountingNumber } from "@/registry/default/motion/counting-number";

const stats = [
  { label: "Components shipped", suffix: "+", value: 164 },
  { label: "GitHub stars", suffix: "K", value: 4.2 },
  { label: "Monthly downloads", suffix: "K", value: 98 },
  { label: "Contributors", suffix: "", value: 37 },
];

export default function CountingNumberStats() {
  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <div className="grid grid-cols-2 gap-8 sm:grid-cols-4">
        {stats.map((stat) => (
          <div className="text-center" key={stat.label}>
            <p className="font-bold text-4xl text-foreground tracking-tight">
              <CountingNumber
                target={stat.value}
                transition={{ duration: 2, ease: "easeOut", type: "tween" }}
              />
              {stat.suffix}
            </p>
            <p className="mt-1 text-muted-foreground text-xs">{stat.label}</p>
          </div>
        ))}
      </div>
    </div>
  );
}
```

### Large Hero Metric

A single full-width counter dominates the hero section with a large typographic treatment. A replay button calls `ref.current.startAnimation()` to re-run the count.

```tsx
"use client";

import { useRef } from "react";
import {
  CountingNumber,
  type CountingNumberRef,
} from "@/registry/default/motion/counting-number";

export default function CountingNumberHero() {
  const ref = useRef<CountingNumberRef>(null);

  return (
    <div className="flex min-h-50 flex-col items-center justify-center gap-6 px-6">
      <div className="text-center">
        <p className="font-medium text-muted-foreground text-sm uppercase tracking-widest">
          Total revenue processed
        </p>
        <p className="mt-2 font-bold text-6xl text-foreground tracking-tight sm:text-7xl">
          $
          <CountingNumber
            autoStart={true}
            from={0}
            ref={ref}
            target={2847593}
            transition={{ duration: 2.5, ease: "easeOut", type: "tween" }}
          />
        </p>
      </div>
      <button
        className="rounded-full bg-accent px-5 py-2 font-medium text-foreground text-sm hover:bg-accent/80"
        onClick={() => ref.current?.startAnimation()}
        type="button"
      >
        Replay
      </button>
    </div>
  );
}
```

### Dashboard Metrics

Three counters inside bordered cards with gradient text colours. Different `duration` values create a staggered feel without any extra wrapper logic.

```tsx
import { CountingNumber } from "@/registry/default/motion/counting-number";

const metrics = [
  {
    color: "from-violet-500 to-purple-600",
    label: "Uptime SLA",
    prefix: "",
    suffix: "%",
    target: 99.9,
    transition: {
      duration: 1.8,
      ease: "easeOut" as const,
      type: "tween" as const,
    },
  },
  {
    color: "from-blue-500 to-cyan-500",
    label: "Requests / sec",
    prefix: "",
    suffix: "K",
    target: 12.4,
    transition: {
      duration: 2,
      ease: "easeOut" as const,
      type: "tween" as const,
    },
  },
  {
    color: "from-emerald-500 to-teal-500",
    label: "Avg latency",
    prefix: "",
    suffix: "ms",
    target: 42,
    transition: {
      duration: 1.5,
      ease: "easeOut" as const,
      type: "tween" as const,
    },
  },
];

export default function CountingNumberDashboard() {
  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <div className="flex w-full max-w-xs flex-col gap-3">
        {metrics.map((m) => (
          <div
            className="flex items-center justify-between rounded-xl border border-border bg-card p-4"
            key={m.label}
          >
            <p className="text-muted-foreground text-sm">{m.label}</p>
            <p
              className={`bg-gradient-to-r ${m.color} bg-clip-text font-bold text-2xl text-transparent tabular-nums`}
            >
              {m.prefix}
              <CountingNumber target={m.target} transition={m.transition} />
              {m.suffix}
            </p>
          </div>
        ))}
      </div>
    </div>
  );
}
```
