---
title: "Zustand optimistische update + rollback"
status: active
audience: [ai-agent, contributor]
language: nl
last_updated: 2026-05-03
when_to_read: "When adding client-side state mutations that need optimistic UI and rollback."
---

# Patroon: Zustand optimistische update + rollback

Gebruik dit patroon bij elke dnd-kit `onDragEnd` handler.

```ts
const { pbiOrder, reorderPbis, rollbackPbis } = usePlannerStore()

async function handleDragEnd(event: DragEndEvent) {
  const { active, over } = event
  if (!over || active.id === over.id) return

  const prevOrder = [...pbiOrder[productId]]
  const newOrder = arrayMove(prevOrder, oldIndex, newIndex)

  // 1. Optimistisch updaten (direct zichtbaar voor gebruiker)
  reorderPbis(productId, newOrder)

  // 2. Persisteren via Server Action
  const result = await reorderPbisAction(productId, newOrder)

  // 3. Rollback bij fout
  if (!result.success) {
    rollbackPbis(productId, prevOrder)
    toast.error('Volgorde opslaan mislukt')
  }
}
```
