# Optimistic UI

Optimistic UI shows the result of an action on screen at once, before the server confirms it, and puts the old state back if the server refuses. It makes a busy screen feel instant, but only when every answer is written onto the data as it is now, not as it was when the action started. Meadowstack's starter does that with two small tools: `setData` with a function and `useTurns`.

Checked 2 December 2026. By Bohuslav Poláček. https://meadowstack.com/glossary/optimistic-ui/

*Changing a person's role in the starter's Team and roles: the new role shows at once, the server's answer wins only if it is still the newest, and a failure puts the old role back.*

From `templates/starter/src/workspace/settings-team.tsx` in the Meadowstack repository:

```tsx
const setRole = async (member: Member, role: Role, undo = false) => {
  if (member.role === role) return;
  const newest = turn(member.id);
  setData(withMember(member.id, { role, roleLabel: roleLabels[role] }));
  try {
    const fresh = await changeRole(person, member.id, role);
    if (newest()) setData(() => fresh);
    if (!undo) {
      toast.success(`${member.name} is now ${roleLabels[role].toLowerCase()}.`, {
        action: {
          label: "Undo",
          onClick: () => setRole({ ...member, role, roleLabel: roleLabels[role] }, member.role, true),
        },
      });
    }
  } catch (error) {
    if (newest()) setData(withMember(member.id, { role: member.role, roleLabel: member.roleLabel }));
    toast.error(error instanceof Error ? error.message : "The role did not change. Please try again.");
```

## Why it matters in a business app

A purchasing manager approves twelve requests in a row, a dispatcher drags six deliveries onto a driver. If each change waits for the server before it shows, the screen stalls after every click and people click twice. Shown at once, the queue moves as fast as the person does.

The danger is overlap. Approve, then undo a second later: if the approval's answer arrives after the undo was shown, a naive screen writes "approved" back and the record steps backwards. Nothing failed, yet the screen now lies.

## How Meadowstack handles it

1. **Change the data on screen first.** `useResource` returns `setData`; the starter calls it before awaiting the api.
2. **After an await, pass a function.** AGENTS.md: optimistic changes after an await go through `setData((current) => …)`. A value built from the data the action started with would put that old data back over everything that happened since.
3. **Take a turn.** `useTurns()` gives each change of one record a number; only the newest may write its answer. A double click or an [undo](https://meadowstack.com/glossary/undo/) right after an approval can no longer step the record back.
4. **Put it back on failure.** The catch restores the old value and says what to do in a toast.
5. **Keep the screen.** After a save the screen stays and the data swaps quietly; [skeletons](https://meadowstack.com/glossary/skeleton-screen/) only on first load or a new filter.

In 2.1 the starter's data is simulated until you connect your backend (`docs/recipes/connect-your-data.md`); the same code runs against the real api.

## Common mistakes

- **Optimism for the irreversible.** Sending money or deleting for good waits for a confirm and the server's answer; optimism is for steps that can be put back.
- **No rollback.** The change stays on screen after the server said no, and the person finds out tomorrow.
- **Reloading after every save.** The list flashes back to loading and loses the scroll position the person was working at.

## Questions

### What happens if the server rejects an optimistic change?

The screen puts the previous value back and a toast says what went wrong and what to do. In the starter's role change the old role returns and the message asks the person to try again.

### Is optimistic UI safe for approvals?

For the approval itself, yes, when undo and a failure put the record back. The permission check still has to happen on the server; the screen only shows the expected result early.

### Why pass a function to setData after an await?

Because other changes may have landed while you waited. A function receives the data on screen now; a value you built earlier would overwrite those changes with old data.

## Related

- [AsyncState: every data view has four states](https://meadowstack.com/components/async-state/) (Components)
- [Loading, error, empty and no results](https://meadowstack.com/patterns/data-states/) (Patterns)
- [Postgres: the person in a transaction setting](https://meadowstack.com/integrations/postgres/) (Integrations)
- [Supabase: the rules in the database](https://meadowstack.com/integrations/supabase/) (Integrations)
- [Undo](https://meadowstack.com/glossary/undo/) (Glossary)
- [Moving one process from a spreadsheet into an app, step by step](https://meadowstack.com/blog/excel-to-business-app/) (Blog)
