| name | apollo-client-patterns |
| description | Use when implementing Apollo Client patterns for queries, mutations, cache management, and local state in React applications. |
| allowed-tools | ["Read","Write","Edit","Grep","Glob","Bash"] |
Apollo Client Patterns
Master Apollo Client for building efficient GraphQL applications with proper
query management, caching strategies, and state handling.
Overview
Apollo Client is a comprehensive state management library for JavaScript that
enables you to manage both local and remote data with GraphQL. It integrates
seamlessly with React and provides powerful caching mechanisms.
Installation and Setup
Installing Apollo Client
npm install @apollo/client graphql
npm install @apollo/client graphql react
npm install graphql-tag @apollo/client/link/error
Basic Configuration
import {
ApolloClient,
InMemoryCache,
createHttpLink,
from
} from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
const httpLink = createHttpLink({
uri: process.env.REACT_APP_GRAPHQL_URI || 'http://localhost:4000/graphql',
});
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem('authToken');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
}
};
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.forEach(({ message, locations, path }) =>
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
}
if (networkError) {
console.error(`[Network error]: ${networkError}`);
}
});
const client = new ApolloClient({
link: from([errorLink, authLink, httpLink]),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
posts: {
merge(existing, incoming) {
return incoming;
}
}
}
}
}
}),
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
errorPolicy: 'all',
},
query: {
fetchPolicy: 'network-only',
errorPolicy: 'all',
},
},
});
export default client;
Provider Setup
import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider } from '@apollo/client';
import client from './apollo/client';
import App from './App';
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root')
);
Core Patterns
1. Basic Queries
import { gql } from '@apollo/client';
export const GET_POSTS = gql`
query GetPosts($limit: Int, $offset: Int) {
posts(limit: $limit, offset: $offset) {
id
title
body
author {
id
name
avatar
}
createdAt
}
}
`;
export const GET_POST = gql`
query GetPost($id: ID!) {
post(id: $id) {
id
title
body
author {
id
name
}
comments {
id
body
author {
id
name
}
}
}
}
`;
import React ;
{ useQuery } ;
{ } ;
() {
{ loading, error, data, refetch, fetchMore } = (, {
: { : , : },
: ,
});
(loading) ;
(error) ;
(
);
}
;
2. Mutations
import { gql } from '@apollo/client';
export const CREATE_POST = gql`
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
id
title
body
author {
id
name
}
createdAt
}
}
`;
export const UPDATE_POST = gql`
mutation UpdatePost($id: ID!, $input: UpdatePostInput!) {
updatePost(id: $id, input: $input) {
id
title
body
}
}
`;
export const DELETE_POST = gql`
mutation DeletePost($id: ID!)
deletePost )
id
`;
, { useState } ;
{ useMutation } ;
{ } ;
{ } ;
() {
[title, setTitle] = ();
[body, setBody] = ();
[createPost, { loading, error }] = (, {
() {
{ posts } = cache.({ : });
cache.({
: ,
: { : [createPost, ...posts] }
});
},
: {
();
();
},
: {
.(, error);
}
});
= () => {
e.();
({
: {
: { title, body }
}
});
};
(
);
}
;
3. Cache Management
import { InMemoryCache, makeVar } from '@apollo/client';
export const cartItemsVar = makeVar([]);
export const isLoggedInVar = makeVar(!!localStorage.getItem('authToken'));
export const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
cartItems: {
read() {
return cartItemsVar();
}
},
isLoggedIn: {
read() {
return isLoggedInVar();
}
},
posts: {
keyArgs: false,
merge(existing = [], incoming, { args }) {
const merged = existing ? existing.slice(0) : [];
const offset = args?.offset || 0;
for (let i = 0; i < incoming.length; i++) {
merged[offset + i] = incoming[i];
}
merged;
}
}
}
},
: {
: {
: {
() {
likes = ();
currentUserId = .();
likes?.( like. === currentUserId);
}
}
}
}
}
});
() {
currentCart = ();
([...currentCart, item]);
}
() {
currentCart = ();
(currentCart.( item. !== itemId));
}
() {
post = client.({
: ,
: gql`
});
(post) {
client.({
: ,
: gql`,
: {
...post,
...updates
}
});
}
}
4. Optimistic Updates
import React from 'react';
import { useMutation } from '@apollo/client';
import { gql } from '@apollo/client';
const LIKE_POST = gql`
mutation LikePost($postId: ID!) {
likePost(postId: $postId) {
id
likesCount
isLiked
}
}
`;
function LikeButton({ post }) {
const [likePost] = useMutation(LIKE_POST, {
variables: { postId: post.id },
optimisticResponse: {
__typename: 'Mutation',
likePost: {
__typename: 'Post',
id: post.id,
likesCount: post.likesCount + 1,
isLiked: true,
}
},
update(cache, { data: { likePost } }) {
cache.modify({
: cache.(post),
: {
() {
likePost.;
},
() {
likePost.;
}
}
});
}
});
(
);
}
;
5. Subscriptions
import { gql } from '@apollo/client';
export const POST_CREATED = gql`
subscription OnPostCreated {
postCreated {
id
title
body
author {
id
name
}
createdAt
}
}
`;
import React from 'react';
import { useQuery, useSubscription } from '@apollo/client';
import { GET_POSTS } from '../graphql/queries';
import { POST_CREATED } from '../graphql/subscriptions';
function RealtimePosts() {
const { data, loading } = useQuery(GET_POSTS);
useSubscription(POST_CREATED, {
onSubscriptionData: ({ client, subscriptionData }) => {
const newPost = subscriptionData.data.postCreated;
client.cache.modify({
fields: {
() {
newPostRef = client..({
: newPost,
: gql`
});
[newPostRef, ...existingPosts];
}
}
});
}
});
(loading) ;
(
);
}
;
6. Lazy Queries
import React, { useState } from 'react';
import { useLazyQuery } from '@apollo/client';
import { gql } from '@apollo/client';
const SEARCH_POSTS = gql`
query SearchPosts($query: String!) {
searchPosts(query: $query) {
id
title
excerpt
}
}
`;
function SearchPosts() {
const [searchTerm, setSearchTerm] = useState('');
const [searchPosts, { loading, data, error, called }] = useLazyQuery(
SEARCH_POSTS,
{
fetchPolicy: 'network-only'
}
);
const handleSearch = (e) => {
e.preventDefault();
if (searchTerm.trim()) {
searchPosts({ variables: { query: searchTerm } });
}
};
return (
<div>
setSearchTerm(e.target.value)}
placeholder="Search posts..."
/>
Search
{loading && Searching...}
{error && Error: {error.message}}
{called && data && (
{data.searchPosts.map(post => (
{post.title}
{post.excerpt}
))}
)}
);
}
;
7. Error Handling
import React from 'react';
import { useQuery } from '@apollo/client';
import { GET_POST } from '../graphql/queries';
function PostWithErrorHandling({ postId }) {
const { loading, error, data } = useQuery(GET_POST, {
variables: { id: postId },
errorPolicy: 'all',
onError: (error) => {
if (error.networkError) {
console.error('Network error:', error.networkError);
}
if (error.graphQLErrors) {
error.graphQLErrors.forEach(({ message, extensions }) => {
if (extensions.code === 'UNAUTHENTICATED') {
window.location.href = '/login';
}
});
}
}
});
if (loading) ;
(error && !data) {
(
);
}
(error && data) {
.(, error);
}
(
);
}
;
8. Pagination Patterns
import React from 'react';
import { useQuery } from '@apollo/client';
import { gql } from '@apollo/client';
const GET_PAGINATED_POSTS = gql`
query GetPaginatedPosts($cursor: String, $limit: Int!) {
posts(cursor: $cursor, limit: $limit) {
edges {
node {
id
title
body
}
cursor
}
pageInfo {
hasNextPage
endCursor
}
}
}
`;
function PaginatedPosts() {
const { data, loading, fetchMore, networkStatus } = useQuery(
GET_PAGINATED_POSTS,
{
variables: { limit: 10 },
notifyOnNetworkStatusChange: true,
}
);
const loadMore = () => {
({
: {
: data...
}
});
};
(loading && networkStatus !== ) ;
(
);
}
;
9. Local State Management
import { gql, makeVar } from '@apollo/client';
export const themeVar = makeVar('light');
export const sidebarOpenVar = makeVar(false);
export const LOCAL_STATE = gql`
query GetLocalState {
theme @client
sidebarOpen @client
}
`;
export const localStateTypePolicies = {
Query: {
fields: {
theme: {
read() {
return themeVar();
}
},
sidebarOpen: {
read() {
return sidebarOpenVar();
}
}
}
}
};
import React from 'react';
import { useQuery } from '@apollo/client';
import { LOCAL_STATE, themeVar } from '../graphql/local';
() {
{ data } = ();
= () => {
newTheme = data. === ? : ;
(newTheme);
.(, newTheme);
};
(
);
}
;
10. Custom Hooks
import { useQuery, useMutation } from '@apollo/client';
import { GET_POSTS, GET_POST } from '../graphql/queries';
import { CREATE_POST, UPDATE_POST, DELETE_POST } from '../graphql/mutations';
export function usePosts() {
const { data, loading, error, refetch } = useQuery(GET_POSTS);
return {
posts: data?.posts || [],
loading,
error,
refetch
};
}
export function usePost(id) {
const { data, loading, error } = useQuery(GET_POST, {
variables: { id },
skip: !id
});
return {
post: data?.post,
loading,
error
};
}
export function useCreatePost() {
const [createPost, { loading, error }] = useMutation(CREATE_POST, {
update(cache, { data: { createPost } }) {
cache.modify({
: {
() {
newPostRef = cache.({
: createPost,
: gql`
});
[newPostRef, ...existingPosts];
}
}
});
}
});
{ createPost, loading, error };
}
() {
{ posts, loading } = ();
{ createPost } = ();
}
Best Practices
- Use fragments - Share field selections across queries
- Implement error boundaries - Gracefully handle errors
- Optimize cache configuration - Configure type policies properly
- Use optimistic updates - Improve perceived performance
- Implement proper loading states - Show feedback during operations
- Avoid over-fetching - Request only needed fields
- Leverage automatic cache - Let Apollo handle caching
- Use reactive variables - Manage local state efficiently
- Implement pagination - Handle large datasets properly
- Monitor network status - Track query states accurately
Common Pitfalls
- Cache inconsistencies - Not updating cache after mutations
- Over-fetching data - Requesting unnecessary fields
- Missing error handling - Not handling network/GraphQL errors
- Polling abuse - Excessive polling causing performance issues
- Not using fragments - Duplicating field selections
- Improper cache normalization - Missing or wrong cache IDs
- Memory leaks - Not cleaning up subscriptions
- Stale data - Using wrong fetch policies
- Missing loading states - Poor user experience
- Auth token issues - Not refreshing expired tokens
When to Use
- Building React applications with GraphQL APIs
- Managing complex application state
- Implementing real-time features
- Creating data-driven UIs
- Building mobile apps with React Native
- Developing admin dashboards
- Creating collaborative applications
- Implementing offline-first features
- Building e-commerce platforms
- Developing social media applications
Resources