Apollo Client basics

Intermediate · 10 min

Set up ApolloClient with an HttpLink and an InMemoryCache, read data with useQuery, and see what the client adds beyond a bare fetch call.

Before thisCalling GraphQL with fetchFields and selection sets

Eric Tech · 10 min

Apollo Client basics

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Eric TechReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • ApolloClient is assembled from a link, which sends operations, and a cache, which stores results.
  • In Apollo Client 4 the React hooks and ApolloProvider come from @apollo/client/react, not the package root.
  • useQuery returns loading, error and data states and re-renders when the cache entry changes.
  • The default fetch policy, cache-first, answers from the cache when it can and only goes to the network for what is missing.

Why a client at all

The fetch helper from the last lesson works, and its limits show quickly. Two components that both show the same book fire two requests. A mutation changes a title and nothing on the screen updates. Loading and error states get reimplemented in every component.

Apollo Client is the most widely used answer to that list. Think of it as a small database in the browser with a query layer on top: you ask for data, it answers from memory when it can, and it asks the server only for what is missing.

Two parts

An ApolloClient is built from exactly two collaborators. A link is the path an operation takes to the server. An InMemoryCache is where results live. Here is a client run against a local GraphQL Yoga server, using @apollo/client 4.3.8:

import { ApolloClient, InMemoryCache, HttpLink, gql } from "@apollo/client";

const client = new ApolloClient({
  link: new HttpLink({ uri: "http://localhost:4000/graphql" }),
  cache: new InMemoryCache(),
});

const BOOKS = gql`
  query Books {
    books { id title author { id name } }
  }
`;

const { data } = await client.query({ query: BOOKS });

This ran as written and returned both books. If you learned Apollo from older material, note what changed in version 4: the uri shortcut no longer builds a link for you (I tried it: the client came up with no link at all), so you pass an explicit HttpLink, and the React integration moved to its own entry point. Hooks are exported from @apollo/client/react. I confirmed that export in the package’s types; I did not render React in this session, so the component below is docs-derived rather than run.

In React

import { ApolloProvider, useQuery } from "@apollo/client/react";

function Books() {
  const { loading, error, data } = useQuery(BOOKS);
  if (loading) return <p>Loading</p>;
  if (error) return <p>{error.message}</p>;
  return <ul>{data.books.map((b) => <li key={b.id}>{b.title}</li>)}</ul>;
}

// <ApolloProvider client={client}><Books /></ApolloProvider>

ApolloProvider puts the client in React context, so any component below it can call a hook. useQuery runs the operation, returns its state, and subscribes the component to the cache. When the cached data behind this query changes, for whatever reason, the component re-renders. That subscription is the part a bare fetch cannot give you. Variables go in as useQuery(BOOK, { variables: { id } }), and a different id triggers a different cache lookup.

Fetch policies

Each query has a fetchPolicy that decides how it uses the cache. The default is cache-first: if every field the query asks for is already stored, answer from memory and make no request. Others you will meet are network-only (always ask the server, still write the result to the cache), cache-and-network (show cached data immediately, then refresh), and no-cache (skip the cache entirely). Choosing among them is how you trade freshness against speed. A dashboard that must be current wants cache-and-network; a settings page that rarely changes is fine with the default.

Check this against what the cache does in practice. In the local run, the first client.query made a request. Asking for the same query again with the default policy would be answered from the cache, because the entities Book:1, Book:2, Author:1 and Author:2 were already stored. The next lesson, the Apollo cache, explains why those keys exist and how they stay consistent.

Alternatives to know about

Apollo is not the only way. urql and Relay make different trade-offs, with a smaller core or compiler-driven fragments. If your app is React with mostly request-response data, a general server-state library such as TanStack Query wrapped around a fetch helper is a legitimate choice, and you lose the normalised cache in exchange for simplicity. Pick Apollo when the same entities show up in many places on screen and you want edits to propagate.

What the video covers

Eric Tech’s video, from July 2024, is a ten-minute tutorial that builds a React front end against a GraphQL back end using Apollo Client. Its title promises a full-stack app, so some of it is server setup that this lesson treats as already done. I could not read a transcript or chapters, so I am only claiming what the title says. Since it was recorded in the Apollo Client 3 era, expect hooks imported from @apollo/client and a uri option on the client; translate those to the version 4 shapes shown above. The runner-up is Laiture’s longer 2021 crash course, which adds lazy queries and mutations but is older and an hour long.

Where this fits

You now have a client that reads and remembers. Next, the Apollo cache opens the box and explains normalisation, which is what makes the rest of Apollo work.

Check yourself

  1. 01What are the two required parts of an ApolloClient?

    A link that sends operations to the server, such as HttpLink, and a cache such as InMemoryCache.

  2. 02What does the default cache-first fetch policy do?

    It returns data from the cache if every requested field is there and only makes a network request otherwise.

  3. 03Why is a client more than a convenience wrapper over fetch?

    It stores results in a normalised cache, deduplicates requests and keeps every component reading the same data consistent.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark