0
0
GraphQLquery~5 mins

Optimistic UI updates in GraphQL

Choose your learning style9 modes available
Introduction

Optimistic UI updates make your app feel faster by showing changes right away before the server confirms them.

When a user submits a form and you want to show the new data immediately.
When liking a post and you want the like count to increase instantly.
When deleting an item and you want it to disappear from the list right away.
When updating a profile and you want to show the new info without waiting.
When toggling a setting and you want the UI to reflect the change instantly.
Syntax
GraphQL
mutation UpdateItem($id: ID!, $newValue: String!) {
  updateItem(id: $id, value: $newValue) {
    id
    value
  }
}

// Use optimisticResponse in your client code like this:
client.mutate({
  mutation: UpdateItem,
  variables: { id: "1", newValue: "New Text" },
  optimisticResponse: {
    updateItem: {
      id: "1",
      value: "New Text",
      __typename: "Item"
    }
  }
})

The optimisticResponse mimics the server response to update the UI immediately.

Make sure the optimistic response matches the shape of the real response.

Examples
This example instantly increases the like count to 101 before the server confirms.
GraphQL
client.mutate({
  mutation: LIKE_POST,
  variables: { postId: "123" },
  optimisticResponse: {
    likePost: {
      id: "123",
      likes: 101,
      __typename: "Post"
    }
  }
})
This example removes a comment from the UI immediately by updating the cache optimistically.
GraphQL
client.mutate({
  mutation: DELETE_COMMENT,
  variables: { commentId: "456" },
  optimisticResponse: {
    deleteComment: {
      id: "456",
      __typename: "Comment"
    }
  },
  update(cache) {
    cache.modify({
      fields: {
        comments(existingComments = [], { readField }) {
          return existingComments.filter(
            commentRef => readField('id', commentRef) !== "456"
          );
        }
      }
    });
  }
})
Sample Program

This mutation adds a new task and shows it immediately in the UI with a temporary id before the server responds.

GraphQL
mutation AddTask($text: String!) {
  addTask(text: $text) {
    id
    text
    completed
  }
}

// Client code example:
client.mutate({
  mutation: AddTask,
  variables: { text: "Buy milk" },
  optimisticResponse: {
    addTask: {
      id: "temp-id-1",
      text: "Buy milk",
      completed: false,
      __typename: "Task"
    }
  }
})
OutputSuccess
Important Notes

If the server later returns an error, you should handle reverting the optimistic update.

Optimistic updates improve user experience by reducing waiting time.

Summary

Optimistic UI updates show changes instantly before server confirmation.

Use optimisticResponse to tell the client what to show.

Make sure to handle errors to keep UI consistent.