0Pricing
React Academy · Lesson

Setting Up Apollo Client in React

Configure ApolloProvider, create the Apollo client with cache and link chain, and connect to a GraphQL API.

Setting Up Apollo Client in React is a free React Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Installing Apollo Client

Install @apollo/client and graphql. The graphql package is a peer dependency that Apollo Client requires for parsing query documents with the gql template tag.

For TypeScript projects, both packages ship their own type definitions, so no @types packages are needed.

Creating the ApolloClient Instance

Instantiate ApolloClient with a cache and a link. The simplest setup: new ApolloClient({ cache: new InMemoryCache(), uri: '/graphql' }). The uri shorthand creates an HttpLink internally.

For more control, build the link chain manually and pass it to the link option instead of uri.

ApolloProvider

Wrap your React application in ApolloProvider with the client prop: ApolloProvider client={client}. This makes the Apollo Client instance available to all descendant components via React context.

Every useQuery and useMutation call in the component tree automatically uses this client without any prop drilling.

InMemoryCache: Normalized Caching

InMemoryCache is Apollo Client's default cache. It normalizes fetched data by type and ID, storing each entity under a unique cache key (e.g., User:1). When any query fetches User:1, all subsequent reads of that entity receive the updated data.

This normalization means updating a user in one mutation automatically updates every query result that includes that user, without any additional code.

HttpLink

HttpLink handles the HTTP transport from Apollo Client to your GraphQL server. Configure it with uri and optionally fetch, headers, and credentials.

For advanced use cases, split links route different operations to different endpoints: subscriptions go over WebSocket (WebSocketLink), queries and mutations go over HTTP (HttpLink).

AuthLink with setContext

Import setContext from @apollo/client/link/context. Create an auth link: const authLink = setContext((_, { headers }) => ({ headers: { ...headers, authorization: 'Bearer ' + getToken() } })). Chain it before HttpLink: authLink.concat(httpLink).

The setContext link runs before each request, dynamically adding auth headers to every operation.

Link Chain Composition

Compose links using ApolloLink.from([authLink, errorLink, httpLink]) or authLink.concat(httpLink). Links are middleware: each link processes the operation and passes it to next(). The last link in the chain sends the actual HTTP request.

Common chains: auth link (add headers) + error link (handle errors) + HTTP link (send request).

Apollo Link Error

Import onError from @apollo/client/link/error. The error link intercepts GraphQL errors and network errors globally. Use it to redirect to a login page on UNAUTHENTICATED errors or display a global error toast on network failures.

The error link must appear before the HTTP link in the chain but can call forward(operation) to retry the request.

Fetch Policy Options

cache-first (default): return cached data immediately; refetch in background if stale. network-only: always fetch from server, update cache. cache-and-network: return cache immediately AND fetch, update UI when response arrives. cache-only: read from cache only, throw if not cached. no-cache: always fetch, never write to cache.

Choose based on data freshness requirements: dashboards often use cache-and-network; user profile forms use network-only.

Setting Default Fetch Policy Globally

Set the default fetchPolicy in the InMemoryCache defaultOptions: new ApolloClient({ defaultOptions: { watchQuery: { fetchPolicy: 'cache-and-network' } } }). Individual useQuery calls can override this per-query.

Setting a sensible global default reduces the boilerplate of specifying fetchPolicy on every hook call.

Apollo Client DevTools

The Apollo Client DevTools browser extension adds an Apollo panel to Chrome DevTools. It shows all cached queries and their current data, lets you explore the normalized cache, and allows re-running queries from the DevTools panel.

Install from the Chrome Web Store and initialize the client with devtools: { enabled: true } (default in development mode).

Apollo Link Chain Composition

In Apollo Client's link chain, where should the errorLink be placed relative to httpLink?

Lesson Recap

Install @apollo/client and graphql, create an ApolloClient with InMemoryCache and link chain, wrap the app in ApolloProvider. The link chain composes authLink (add tokens), errorLink (global error handling), and httpLink (HTTP transport). Fetch policy controls cache vs network priority; InMemoryCache normalizes entities by type+id.

Apollo DevTools browser extension makes cache inspection and debugging straightforward.

Frequently asked questions

Is the “Setting Up Apollo Client in React” lesson free?

Yes — the full text of “Setting Up Apollo Client in React” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Setting Up Apollo Client in React”?

Configure ApolloProvider, create the Apollo client with cache and link chain, and connect to a GraphQL API. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Setting Up Apollo Client in React” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. GraphQL Fundamentals for React Developers
  2. Setting Up Apollo Client in React
  3. useQuery and useMutation Hooks
  4. Apollo Cache: Normalization and Updates
← Back to React Academy