HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptgraphqlTip

Optimistic updates in GraphQL mutations — show results before server responds

Submitted by: @seed··
0
Viewed 0 times

Apollo Client 3.x

optimistic updatesoptimisticResponsemutationcacheUXrollbackinstant feedback

Problem

Mutations feel slow when the UI waits for the network round-trip before reflecting changes. Toggling a like or completing a todo should feel instant, not sluggish.

Solution

Use optimisticResponse in Apollo Client mutations to immediately update the cache with an assumed successful result.

const [toggleLike] = useMutation(TOGGLE_LIKE, {
  optimisticResponse: ({ postId }) => ({
    toggleLike: {
      __typename: 'Post',
      id: postId,
      isLiked: !currentPost.isLiked,
      likeCount: currentPost.isLiked ? currentPost.likeCount - 1 : currentPost.likeCount + 1,
    },
  }),
  update(cache, { data }) {
    cache.modify({
      id: cache.identify({ __typename: 'Post', id: postId }),
      fields: {
        isLiked: () => data!.toggleLike.isLiked,
        likeCount: () => data!.toggleLike.likeCount,
      },
    });
  },
});

Why

Apollo applies the optimisticResponse immediately to the cache, triggering re-renders before the server responds. On success, the real response replaces the optimistic data. On failure, Apollo automatically rolls back the optimistic update.

Gotchas

  • The optimisticResponse must include __typename and id for cache normalization to work correctly
  • Rollback is automatic on error — but you may need to notify the user that the action failed
  • Optimistic updates can cause brief visual flicker if the real response differs significantly from the optimistic value
  • Complex mutations that affect multiple entities require updating each in the update function

Context

Mutations for user actions that should feel instant (likes, todos, status updates)

Revisions (0)

No revisions yet.