Skip to content

NarixHine/uni-chem / .agents/skills/safe-action-hooks

safe-action-hooks

Verified

Use when executing next-safe-action actions from React client components -- useAction, useOptimisticAction, handling status/callbacks (onSuccess/onError/onSettled), execute vs executeAsync, or optimistic UI updates

FileKindSize
SKILL.mdskill md6.5 KB
optimistic-updates.mdmarkdown3.0 KB
status-callbacks.mdmarkdown5.2 KB
throw-on-navigation.mdmarkdown4.5 KB
use-action.mdmarkdown4.2 KB
use-state-action.mdmarkdown7.3 KB

optimistic-updates.md

View on GitHub
# Optimistic Updates

## useOptimisticAction

Wraps `React.useOptimistic` to immediately update the UI while the server action runs in the background.

```tsx
import { useOptimisticAction } from "next-safe-action/hooks";
```

### Required Props

```ts
useOptimisticAction(safeActionFn, {
  currentState: State,          // Current server state
  updateFn: (state, input) => State, // Produces the optimistic state
  // ...optional callbacks
});
```

- `currentState` — The current state from the server (typically from a Server Component prop or data fetch)
- `updateFn` — A pure function that computes the optimistic state from the current state and the action input

### How It Works

1. User calls `execute(input)`
2. `updateFn(currentState, input)` runs synchronously → `optimisticState` updates immediately
3. The action executes on the server
4. When the server responds, `currentState` prop updates via revalidation → `optimisticState` reverts to the real state

## Complete Example: Like Button

```tsx
"use client";

import { useOptimisticAction } from "next-safe-action/hooks";
import { toggleLike } from "@/app/actions";

interface Props {
  postId: string;
  likes: number;
  isLiked: boolean;
}

export function LikeButton({ postId, likes, isLiked }: Props) {
  const { execute, optimisticState } = useOptimisticAction(toggleLike, {
    currentState: { likes, isLiked },
    updateFn: (state) => ({
      likes: state.isLiked ? state.likes - 1 : state.likes + 1,
      isLiked: !state.isLiked,
    }),
    onError: ({ error }) => {
      // Optimistic state auto-reverts on error
      toast.error("Failed to update like");
    },
  });

  return (
    <button onClick={() => execute({ postId })}>
      {optimisticState.isLiked ? "❤️" : "🤍"} {optimisticState.likes}
    </button>
  );
}
```

## List Operations

### Optimistic Add

```tsx
const { execute, optimisticState } = useOptimisticAction(addTodo, {
  currentState: todos,
  updateFn: (state, input) => [
    ...state,
    { id: crypto.randomUUID(), title: input.title, completed: false },
  ],
});
```

### Optimistic Delete

```tsx
const { execute, optimisticState } = useOptimisticAction(deleteTodo, {
  currentState: todos,
  updateFn: (state, input) =>
    state.filter((todo) => todo.id !== input.todoId),
});
```

### Optimistic Update

```tsx
const { execute, optimisticState } = useOptimisticAction(toggleTodo, {
  currentState: todos,
  updateFn: (state, input) =>
    state.map((todo) =>
      todo.id === input.todoId
        ? { ...todo, completed: !todo.completed }
        : todo
    ),
});
```

## Key Points

- `optimisticState` updates **synchronously** before the server call
- When the server response arrives and `currentState` prop updates (via revalidation), the optimistic state is replaced by the real state
- On error, `optimisticState` automatically reverts to `currentState`
- The `updateFn` should be a **pure function** — no side effects
- `execute` and `executeAsync` both trigger the optimistic update
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 322kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 198kUpdated Claude CodeCodexVerifiedInstall