# Like Button

> Animated like button for React and shadcn: the heart pops with a burst of sparks, and the optimistic count reverts if saving fails.

A heart that pops to 1.25 with a ring and eight sparks when liked, deflates quietly when unliked, and rolls its count. Optimistic: it flips at once and rolls back if onLikedChange rejects.

Also known as a heart button.

- Tier: Free (MIT)
- Interaction: Press
- Page: https://eased.dev/components/like-button
- Installs: motion
- Registry: https://eased.dev/r/like-button.json

## Install

```bash
npx shadcn add https://eased.dev/r/like-button.json
```

A heart that pops and bursts when liked, deflates quietly when unliked, and rolls its count.

## When to use

- Likes, favourites and upvotes on posts, comments, products and listings.
- Anywhere a count should visibly respond to the reader.

## When not to use

- Saving to a list or bookmarking: use a Button with a TextSwap label.
- Multiple reactions: use emoji reactions.

## Usage

```tsx example.tsx
import { LikeButton } from "@/components/eased/like-button/like-button";

export function Example({ post }: { post: Post }) {
  return (
    <LikeButton
      defaultLiked={post.likedByMe}
      count={post.likes}
      format={{ notation: "compact" }}
      onLikedChange={(liked) => fetch(`/api/posts/${post.id}/like`, { method: liked ? "POST" : "DELETE" })}
    />
  );
}
```

## API reference

### LikeButton

| Prop | Type | Default | Description |
|---|---|---|---|
| `liked` | `boolean` | | Controlled state. |
| `defaultLiked` | `boolean` | `false` | Uncontrolled start. |
| `onLikedChange` | `(liked) => void \| Promise` | | Return a promise for an optimistic toggle that rolls back on rejection. |
| `count` | `number` | | The count as loaded (including or excluding this viewer's like as it was then). Omit to hide it. Live updates from others are fine. |
| `format` / `locale` | `Intl.NumberFormatOptions` / `Intl.LocalesArgument` | | Count formatting. |
| `size` | `"sm" \| "md"` | `"sm"` | 32px or 36px. |
| `aria-label` | `string` | `"Like"` | The count is appended. |

Other button props pass through. Set `--like` (and `--like-alt` for alternate sparks) to recolour; defaults are the danger and warning tokens.

## Keyboard

| Key | Action |
|---|---|
| `Enter` / `Space` | Toggles the like. |

## Accessibility

- A toggle button (`aria-pressed`) named "Like, 1,286". The rolling digits are hidden from assistive tech.
- The count reserves two digits, so hearts in a column of rows line up.

## Motion

Liking scales the heart to 1.25 in 120ms, then the bouncy spring brings it back, while a ring opens and fades and eight sparks fly out and shrink over 500ms. The fill grows from the centre on the snappy spring. Unliking dips to 0.86 and springs back with no burst; the fill fades in 120ms. The count rolls in the direction of change. All of it is interruptible. Reduced motion: no pop, no burst, the fill and count change at once.

## Notes for AI

Use it for any like/favourite toggle with a count. Pass the server's count and the viewer's initial state; return the request promise from `onLikedChange` to get optimistic rollback for free.

Do not add one to the count yourself when liked; the component applies the viewer's change. Do not wrap it in another button.

## Related

- [Number Roll](/components/number-roll): the count's engine.
- [Button](/components/button): for actions that are not toggles.

## Example

`components/eased/like-button/like-button-demo.tsx`

```tsx
"use client";

import { useInView } from "motion/react";
import { useEffect, useRef, useState } from "react";
import { Avatar } from "../avatar/avatar";
import { DemoFrame } from "../lib/demo-frame";
import { useSafeReducedMotion } from "../lib/motion";
import { rowGrid, rowGridRow } from "../lib/layout";
import { LikeButton } from "./like-button";

const REPLIES = [
  { name: "Jonas Weber", when: "2h", text: "The divider snapping to 50 is so good.", count: 18 },
  { name: "Priya Raman", when: "1h", text: "Shipping this in our changelog today.", count: 7 },
  { name: "Sam Lindqvist", when: "12m", text: "Does it work with two themes side by side?", count: 0 },
];

/** A changelog post: like it for the burst; other readers keep liking it, so the count rolls on its own. */
export function LikeButtonDemo() {
  const [others, setOthers] = useState(1286);
  const root = useRef<HTMLDivElement>(null);
  const inView = useInView(root, { amount: 0.5 });
  const reduced = useSafeReducedMotion();

  // Someone else likes the post every few seconds, while the demo is on screen.
  useEffect(() => {
    if (!inView || reduced) return;
    const t = window.setInterval(() => setOthers((n) => n + 1 + Math.floor(Math.random() * 2)), 3200);
    return () => window.clearInterval(t);
  }, [inView, reduced]);

  return (
    <DemoFrame title="Changelog" meta="Oct 18">
      <div ref={root} className="flex min-h-0 flex-1 flex-col overflow-hidden">
        <article className="flex flex-col gap-3 border-b border-line-subtle p-(--pad)">
          <div className="flex items-center gap-2.5">
            <Avatar name="Maya Okafor" size="md" />
            <div className="min-w-0">
              <p className="truncate text-ui font-medium text-text">Maya Okafor</p>
              <p className="text-ui-sm text-text-muted">Design engineer · 3h</p>
            </div>
          </div>
          <p className="text-ui text-pretty text-text-secondary">
            Image Compare is live: drag the divider, flick it to an edge, or tab to it and use the arrows. It compares
            anything, not just images.
          </p>
          <div className="-ms-2.5 flex items-center gap-1">
            <LikeButton size="md" count={others} aria-label="Like post" />
            <span className="inline-flex h-control-md items-center gap-2 px-2.5 text-ui text-text-muted tabular-nums">
              <svg viewBox="0 0 16 16" className="size-[18px]" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" aria-hidden>
                <path d="M2.75 7.6c0-2.6 2.3-4.35 5.25-4.35s5.25 1.75 5.25 4.35S10.95 12 8 12c-.6 0-1.17-.07-1.7-.2L3.4 13l.75-2.3A4.1 4.1 0 0 1 2.75 7.6Z" />
              </svg>
              3
            </span>
          </div>
        </article>
        <ul className={`${rowGrid} gap-x-2.5 px-(--pad) py-2 [--col:3.5rem]`}>
          {REPLIES.map((r) => (
            <li key={r.name} className={`${rowGridRow} items-start py-2`}>
              <Avatar name={r.name} size="sm" className="mt-px" />
              <div className="min-w-0">
                <p className="truncate text-ui-sm text-text">
                  <span className="font-medium">{r.name}</span> <span className="text-text-muted">· {r.when}</span>
                </p>
                <p className="truncate text-ui-sm text-text-secondary">{r.text}</p>
              </div>
              <LikeButton count={r.count} aria-label={`Like ${r.name}'s reply`} className="-me-2 -mt-1.5 justify-self-end" />
            </li>
          ))}
        </ul>
      </div>
    </DemoFrame>
  );
}
```
