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.

Apollo Client Setup
import { ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
  uri: "/graphql",
  cache: new InMemoryCache()
});

export default client;
💡 The Apollo Client instance contains the GraphQL endpoint configuration and cache. It should generally be created once and provided to the application rather than instantiated repeatedly inside components.
Key Takeaways
  • Create a shared Apollo Client instance.
  • Use InMemoryCache for Apollo's normalized cache.
  • Provide the client to React through the Apollo provider.
  • Centralize authentication and transport configuration.
Knowledge Check

Why should an Apollo Client instance generally be shared rather than recreated for every React component?