Redux
Advanced

Optimistic Updates

Implement immediate UI updates before server confirmation with RTK Query.

25 min
1 sections
optimistic
updates
ux
1

01. Optimistic Updates Pattern

Section 1 of 1

Update UI immediately when user acts, assume success, rollback if the server fails.

typescript
export const api = createApi({
  endpoints: (builder) => ({
    updateTodo: builder.mutation({
      query: ({ id, ...patch }) => ({
        url: `/todos/${id}`,
        method: 'PATCH',
        body: patch,
      }),
      async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
        // Optimistic update
        const patchResult = dispatch(
          api.util.updateQueryData('getTodos', undefined, (draft) => {
            const todo = draft.find((t) => t.id === id);
            if (todo) Object.assign(todo, patch);
          })
        );
        try {
          await queryFulfilled;
        } catch {
          patchResult.undo(); // Rollback on error
        }
      },
    }),
  }),
});

Exercise

Add Optimistic Update

Practice

Implement an optimistic update for a like button that immediately toggles the like state.

Back to Course