# useOptimistic()

> The `useOptimistic()` hook in React shows a different state while an async action is in progress.

## What does useOptimistic do in React?

The hook that shows a temporary optimistic value while an action is running. For example, it displays a new message instantly before the server confirms it and automatically reverts if the action fails.

- Topic: Hooks
- Type: hook

## Example

Wrong:

```jsx
const [optimisticLikes, addLike] = useOptimistic(likes, (n) => n + 1);
function handleClick() {
  addLike();
  saveLike();
}
```

Right:

```jsx
const [optimisticLikes, addLike] = useOptimistic(likes, (n) => n + 1);
function handleClick() {
  startTransition(async () => {
    addLike();
    const total = await saveLike();
    startTransition(() => setLikes(total));
  });
}
```

The optimistic update runs inside a transition and the real state is set after the save, so the count never jumps back.

## Common mistakes

- Calling the setter outside a transition and getting a warning with no optimistic update.
- The item disappears after saving because the real list was never updated.

## Key points

- The optimistic setter is called inside an action or `startTransition`, not in a plain event handler.
- The real state is updated after the action, since the optimistic value is dropped when it ends.
- A failed request shows an error, as the UI silently reverts to the real state.

## Interview questions

### Why does my optimistic value revert immediately?

The action finished but the real state was never updated. Set the real state from the server result before the action ends.

### useOptimistic vs useState: when should I use which?

Use `useState` for the real value. Use `useOptimistic` for a temporary value shown only while an action is running.

## Related cards

- [Actions](https://wonderium.dev/react/actions.md)
- [useActionState()](https://wonderium.dev/react/use-action-state.md)
- [useTransition()](https://wonderium.dev/react/use-transition.md)
- [startTransition()](https://wonderium.dev/react/start-transition.md)
- [useFormStatus()](https://wonderium.dev/react/use-form-status.md)

---

- Level: [React](https://wonderium.dev/react.md)
- HTML version: https://wonderium.dev/react/use-optimistic
- Last updated: 2026-11-25
