Setting Up Apollo Client in React
A React application typically creates an Apollo Client instance and provides it to the component tree.
Conceptually:
const client = new ApolloClient({
uri: "/graphql",
cache: new InMemoryCache()
});
The application then provides the client through Apollo's React integration.
<ApolloProvider client={client}>
<App />
</ApolloProvider>
Components below the provider can use GraphQL hooks such as useQuery and useMutation.
The InMemoryCache is a normalized cache. It can store entities and references rather than simply caching entire query responses as opaque blobs.
In production applications, the Apollo Client setup often also includes an authentication link, error handling, retry behavior, upload support, tracing headers, or other transport concerns.
Keep transport configuration centralized instead of recreating clients inside individual React components.
import { ApolloClient, InMemoryCache } from "@apollo/client";
const client = new ApolloClient({
uri: "/graphql",
cache: new InMemoryCache()
});
export default client;- Create a shared Apollo Client instance.
- Use
InMemoryCachefor Apollo's normalized cache. - Provide the client to React through the Apollo provider.
- Centralize authentication and transport configuration.
Why should an Apollo Client instance generally be shared rather than recreated for every React component?