Apollo Client Setup and Configuration
What you'll learn: How to install and wire up Apollo Client so your React app can fetch GraphQL data with intelligent caching and predictable behavior.
What Apollo Client Does
Apollo Client is a comprehensive GraphQL client that manages server communication, caching, and UI updates. Think of it as the "control center" for all your GraphQL requests—it handles fetching, stores responses intelligently, and keeps your components synchronized with that data.
Installation
First, install the required packages:
npm install @apollo/client graphql
The @apollo/client package includes everything: the core client, React hooks, and caching utilities. The graphql package provides GraphQL's type system.
Basic Configuration
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
// Create the client instance
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache()
});
// Wrap your app
function App() {
return (
<ApolloProvider client={client}>
<YourComponents />
</ApolloProvider>
);
}
Cache Policies
The InMemoryCache is Apollo's normalized cache. You can configure how it identifies and merges data:
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
posts: {
merge(existing, incoming) {
return incoming; // Replace strategy
}
}
}
}
}
});
Link Setup
For advanced scenarios (auth headers, error handling), use Apollo Link:
import { HttpLink, ApolloLink } from '@apollo/client';
const httpLink = new HttpLink({ uri: '/graphql' });
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: { authorization: `Bearer ${token}` }
});
return forward(operation);
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
The ApolloProvider works like React Context—it makes the client available throughout your component tree.
Key Takeaway: Apollo Client setup involves creating a client with a GraphQL endpoint and cache, optionally configuring links for middleware-like behavior, then wrapping your app in ApolloProvider to enable data fetching throughout your component tree.