Graphql client patterns

From Intense-Visions/harness-engineering · View interactive version

Graphql client patterns is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Structure GraphQL client code with fragments, cache normalization, and optimistic updates for responsive UIs

How to use this skill

Skill file

GraphQL Client Patterns

Structure GraphQL client code with fragments, cache normalization, and optimistic updates for responsive UIs

When to Use

Instructions

  1. Co-locate queries with the components that use them. Define the query in the same file (or adjacent .graphql file) as the component that renders the data. This makes data dependencies explicit.
const GET_USER = gql`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
      ...UserAvatar
    }
  }
  ${USER_AVATAR_FRAGMENT}
`;

function UserProfile({ userId }: { userId: string }) {
  const { data, loading, error } = useQuery(GET_USER, { variables: { id: userId } });
  if (loading) return <Skeleton />;
  if (error) return <ErrorBanner error={error} />;
  return <div>{data.user.name}</div>;
}
  1. Use fragments to share field selections across queries. Fragments prevent field duplication and ensure components always receive the fields they need, regardless of which query fetches the data.
const USER_AVATAR_FRAGMENT = gql`
  fragment UserAvatar on User {
    id
    avatarUrl
    name
  }
`;

// Reuse in any query that needs avatar data
  1. Configure the normalized cache with typePolicies. Apollo Client's InMemoryCache normalizes by __typename:id. Customize merge behavior, pagination, and key fields in typePolicies.
const cache = new InMemoryCache({
  typePolicies: {
    User: {
      keyFields: ['id'],
    },
    Query: {
      fields: {
        feed: offsetLimitPagination(),
      },
    },
  },
});
  1. Use optimistic responses for instant UI feedback. When the user performs a mutation, provide an optimisticResponse that mirrors the expected server response. The cache updates immediately; the real response replaces it when it arrives.
const [toggleLike] = useMutation(TOGGLE_LIKE, {
  optimisticResponse: {
    toggleLike: {
      __typename: 'Post',
      id: postId,
      isLiked: !currentlyLiked,
      likeCount: currentlyLiked ? count - 1 : count + 1,
    },
  },
});
  1. Choose the right cache update strategy after mutations:
const [addComment] = useMutation(ADD_COMMENT, {
  update(cache, { data: { addComment } }) {
    cache.modify({
      id: cache.identify({ __typename: 'Post', id: postId }),
      fields: {
        comments(existing = []) {
          const newRef = cache.writeFragment({
            data: addComment,
            fragment: COMMENT_FIELDS,
          });
          return [...existing, newRef];
        },
      },
    });
  },
});
  1. Handle loading and error states consistently. Create reusable patterns — a <QueryResult> wrapper component or custom hooks that standardize loading/error/empty states across the app.
  1. Use fetchPolicy intentionally.
  1. Avoid over-fetching with field-level selections. Only request the fields the component needs. The normalized cache works best when queries request predictable field sets.

Details

Apollo Client vs. urql vs. lightweight clients: Apollo Client offers the richest cache and ecosystem but is the largest bundle (~40KB). urql is smaller (~15KB) with a plugin-based architecture (exchanges). For simple use cases, graphql-request (~5KB) provides a fetch wrapper without caching.

Cache normalization explained: Apollo splits query results into individual objects keyed by __typename:id. When a mutation returns an updated User, every query that references that user sees the update. This works only if every queried type has a stable id field.

Fragment colocation pattern (Relay-style): Each component declares a fragment for the data it needs. Parent components spread those fragments into their queries. This creates a clear contract: the component works if and only if its fragment is included.

Polling vs. subscriptions: Use pollInterval for data that changes infrequently (dashboard stats). Use subscriptions for real-time data (chat messages, live scores). Polling is simpler to implement and does not require WebSocket infrastructure.

Common mistakes:

Source

https://www.apollographql.com/docs/react/

Process

  1. Read the instructions and examples in this document.
  2. Apply the patterns to your implementation, adapting to your specific context.
  3. Verify your implementation against the details and edge cases listed above.

Harness Integration

Success Criteria

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.