SyntaxStudy
Sign Up
GraphQL Optimistic UI and Cache Updates with Apollo Client
GraphQL Beginner 1 min read

Optimistic UI and Cache Updates with Apollo Client

Apollo Client maintains a normalized in-memory cache keyed by __typename + id. When a mutation response returns the updated object, Apollo automatically updates every query in the cache that referenced that object, keeping the UI consistent without manual state management. Optimistic responses let the UI update immediately before the server confirms the mutation. Apollo rolls back the optimistic update if the server returns an error, giving users instant feedback while maintaining data integrity.
Example
// Apollo Client mutation with optimistic UI
import { useMutation, gql } from '@apollo/client';

const LIKE_POST = gql`
  mutation LikePost($id: ID!) {
    likePost(id: $id) {
      id
      likeCount
      likedByMe
    }
  }
`;

function LikeButton({ post }) {
  const [likePost] = useMutation(LIKE_POST, {
    // Optimistic response — shown immediately
    optimisticResponse: {
      likePost: {
        __typename: 'Post',
        id: post.id,
        likeCount: post.likeCount + 1,
        likedByMe: true,
      },
    },
    // Manual cache update for lists not auto-updated
    update(cache, { data: { likePost } }) {
      cache.modify({
        id: cache.identify(likePost),
        fields: {
          likeCount: () => likePost.likeCount,
          likedByMe: () => likePost.likedByMe,
        },
      });
    },
  });

  return (
    <button onClick={() => likePost({ variables: { id: post.id } })}>
      {post.likedByMe ? '♥' : '♡'} {post.likeCount}
    </button>
  );
}