kipluo
React6 min read3 steps

How to Create an Animated Add-to-Cart Button

E-commerce buttons fail in subtle ways: double-charges on rapid clicks, layout jitter when labels swap length, and silent state transitions for screen readers. Model the button as a strict finite state machine.

You needReact 18+Async/AwaitARIA live regions
Loading demo
Click repeatedly to see state morphing and rapid-click resilience in action.Component page

1. Model Idle -> Pending -> Done -> Error explicitly

Avoid juggling three separate booleans (isLoading, isSuccess, hasError). A single status union guarantees impossible states like 'loading and error at the same time' can never happen.

AddToCartButton.tsx
import { useEffect, useRef, useState } from "react";

type Status = "idle" | "pending" | "done" | "error";

export function AddToCartButton({ onAdd }: { onAdd: () => Promise<void> }) {
  const [status, setStatus] = useState<Status>("idle");
  const timerRef = useRef<number | null>(null);

  useEffect(() => () => { if (timerRef.current) clearTimeout(timerRef.current); }, []);

  const handleClick = async () => {
    if (status === "pending") return; // Prevent double-submission
    if (timerRef.current) clearTimeout(timerRef.current);
    setStatus("pending");
    try {
      await onAdd();
      setStatus("done");
      timerRef.current = window.setTimeout(() => setStatus("idle"), 1600);
    } catch {
      setStatus("error");
      timerRef.current = window.setTimeout(() => setStatus("idle"), 1800);
    }
  };

  const label = {
    idle: "Add to cart",
    pending: "Adding…",
    done: "Added ✓",
    error: "Try again",
  }[status];

  return (
    <button
      type="button"
      onClick={handleClick}
      aria-busy={status === "pending"}
      className="inline-flex min-w-36 items-center justify-center rounded-full bg-zinc-900 px-5 py-2.5 text-sm font-semibold text-white transition-all duration-200 active:scale-95"
    >
      <span aria-live="polite">{label}</span>
    </button>
  );
}

2. Prevent horizontal layout shift during label swaps

When 'Add to cart' shrinks to 'Added ✓', neighboring buttons jump sideways. Either set a stable min-width or animate the button's measured width smoothly on a spring while keeping the button centered.

3. Clear reset timers on unmount or re-trigger

If a user clicks again right after success—or navigates to checkout before your 1600ms reset fires—an uncancelled setTimeout can stomp the newer state. Store the timeout ID in a ref and clear it on both re-entry and unmount.

Accessibility checklist

Tick each one off as you check your build. Your ticks stay in this browser.

0 of 3 checked

Build it yourself or install it

Build it yourself when

A simple min-width button with CSS active:scale-95 already meets your storefront needs.

Install Kipluo when

You want spring width morphing, animated check/spinner/shake feedback, and synthesized chime/bonk cues.

Keep building