Course contentsShow
← React
Lesson 1798 of 2,39642. Data Fetching LibrariesFree lesson

Optimistic Updates for Lists

Apply optimistic patterns to list mutations: adding items, removing items, and updating items in arrays.

Optimistic Updates for Lists

You'll learn how to apply optimistic UI patterns to list operations—adding, removing, and updating items in arrays—so your interface feels instant even when the server is slow.

The Pattern for Arrays

When you optimistically update a list, you're manipulating an array in the cache before the server confirms the change. This means you need to handle three common operations:

Adding items: Insert the new item into the cached array immediately (usually at the start or end).

Removing items: Filter out the item by its ID from the cached array.

Updating items: Map through the array and replace the matching item with its updated version.

Each operation follows the same onMutate → onError rollback pattern you learned, but now you're working with array methods.

The Code Shape

const addItemMutation = useMutation({
  mutationFn: addItem,
  onMutate: async (newItem) => {
    await queryClient.cancelQueries(['items']);
    const previous = queryClient.getQueryData(['items']);
    
    // Add to list optimistically
    queryClient.setQueryData(['items'], (old) => [newItem, ...old]);
    
    return { previous };
  },
  onError: (err, newItem, context) => {
    queryClient.setQueryData(['items'], context.previous);
  }
});

For removal, you'd use .filter(item => item.id !== deletedId). For updates, you'd use .map(item => item.id === updatedItem.id ? updatedItem : item).

The key insight: your snapshot (previous) preserves the entire original array. If the mutation fails, you restore the whole list, not just the changed item.

Key Takeaway: Optimistic list updates use array methods (spread/concat, filter, map) inside setQueryData to immediately reflect additions, deletions, and edits before the server responds, with full-array rollback on error.