Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Clients and Transport

Clients, Apollo and Code Generation

Compare plain fetch with Apollo Client, urql and Relay, and learn normalized caching, optimistic updates and generating TypeScript types from a schema.

You can talk to a GraphQL API with plain fetch, as shown in GraphQL over HTTP. For a small script that is often enough. For an application with many screens, you quickly need the same things again and again: caching, loading and error states, refetching after mutations, and type safety. GraphQL client libraries package those features.

None of these libraries run on this site, so the library code below is read-only and written conservatively, in the common shapes the libraries use. The runnable example is a stand-in normalized cache in plain JavaScript, which shows the idea at the heart of the big clients. For how React fetches data in general, see React data fetching.

What a client adds

Cache Reuse data between screens.
States Loading, error and data.
Optimism Update the UI before the server replies.
Types Generated from the schema.
1 / 2

Plain fetch versus a client library

Need Plain fetch Client library
Send a query A few lines One hook or function call
Cache between screens You build it Built in
Loading and error state Hand-written Built in
Refetch after a mutation Manual Cache updates or refetch rules
Subscriptions Manual WebSocket code Built-in links or plugins
Bundle size Zero Tens of kilobytes

Plain fetch is a fine choice for a script, a server-to-server call, or a page with one or two queries. Reach for a library when many components share data.

The main libraries

All three are widely used, and all three speak the same HTTP protocol, so you can change your mind later.

  • Apollo Client: the most popular and feature-rich option. It has a normalized cache, local state, many integrations and a large ecosystem. It is also the largest.
  • urql: smaller and more modular. It starts with a simple document cache and lets you add a normalized cache, retries and other behavior as "exchanges".
  • Relay: made by the team that created GraphQL. It is strict and powerful: every component declares its own data needs with a fragment, a compiler checks and optimizes them, and pagination follows the connection spec from Pagination: Offset, Cursor and Connections. The learning curve is higher, and it expects a schema designed for it, with globally unique IDs.

Choose by team size and needs, not by popularity alone. A small app rarely needs Relay; a huge app with many teams may love it.

A hook in React (read-only)

In Apollo Client, a component asks for data with a hook. The shape is typical of the libraries (check the current documentation for exact option names):

JSX
import { gql, useQuery } from "@apollo/client";

const GET_BOOKS = gql`
  query GetBooks($genre: String!) {
    books(genre: $genre) {
      id
      title
      author { id name }
    }
  }
`;

function BookList({ genre }) {
  const { data, loading, error } = useQuery(GET_BOOKS, { variables: { genre } });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Something went wrong: {error.message}</p>;

  return (
    <ul>
      {data.books.map((book) => (
        <li key={book.id}>{book.title} by {book.author.name}</li>
      ))}
    </ul>
  );
}

The component only describes what it needs. The library sends the request, caches the result, and re-renders when the cached data changes.

Hooks in React: useQuery and useMutation in depth

The earlier sketch showed useQuery in one breath. In a real component you deal with three states (loading, error, data), variables that change, retrying after a failure and writing data with mutations. This section goes through those, then shows the same screen with plain fetch and with Axios, so you can judge what a client library gives you. The React and Apollo code is read-only (the site cannot install Apollo), and the runnable stand-in models the state machine inside the hooks without React.

The three states of a query

useQuery returns an object whose main fields are loading, error and data. Handle them in this order:

JSX
function BookList() {
  const { data, loading, error, refetch } = useQuery(GET_BOOKS);

  if (loading && !data) return <Spinner />;          // first load only
  if (error && !data) return <ErrorBox error={error} onRetry={() => refetch()} />;

  return (
    <>
      {error && <Banner>Showing saved data. {error.message}</Banner>}
      <ul>{data.books.map((b) => <li key={b.id}>{b.title}</li>)}</ul>
    </>
  );
}

Two habits keep screens from flickering. Test loading && !data so a background refetch does not replace the list with a spinner, and show an error banner above existing data instead of throwing the data away. Remember also the two kinds of failure from How Execution Works and How Errors Behave: a network error (the request failed, no data) and GraphQL errors (the server answered with errors, maybe with partial data). Apollo exposes both through error and lets you choose an errorPolicy (none, all or ignore) to decide whether partial data is kept.

Variables, skipping and refetching

Pass variables in options, and the hook refetches when they change:

JSX
const { data } = useQuery(GET_BOOK, {
  variables: { id: bookId },
  skip: !bookId,                  // do not run until we have an id
  fetchPolicy: 'cache-and-network',
});

skip stops a query from running (for example, until a user selects something). fetchPolicy controls cache use: cache-first (default) answers from the cache if it can, network-only always asks the server, and cache-and-network shows cached data immediately, then updates it. For polling use pollInterval, and for a manual reload call refetch().

useMutation

A mutation is not run when the component renders. The hook gives you a function to call, plus its state:

JSX
const [addBook, { loading, error }] = useMutation(ADD_BOOK, {
  update(cache, { data }) {
    cache.modify({
      fields: {
        books(existing = []) {
          const ref = cache.writeFragment({ data: data.addBook, fragment: BOOK_FIELDS });
          return [...existing, ref];
        },
      },
    });
  },
});

<form onSubmit={async (e) => {
  e.preventDefault();
  try {
    await addBook({ variables: { title } });
  } catch {
    // the error is also in the hook state; the promise rejects unless you pass onError
  }
}}>
  <button disabled={loading}>Add</button>
  {error && <p role="alert">{error.message}</p>}
</form>

After a mutation, the list on screen must change. Your options, from simplest to most refined, are refetchQueries: ['GetBooks'] (ask the server again), the update function above (write the new object into the cache by hand), or returning enough fields that the normalized cache updates by itself, which works for edits to existing objects (see Normalized caching, below). Disable the button while loading to prevent double submits.

The same screen with fetch or Axios

A client library is optional. A GraphQL request is an HTTP POST, so fetch works:

JSX
function BookList() {
  const [state, setState] = useState({ loading: true });

  useEffect(() => {
    const controller = new AbortController();
    fetch('/graphql', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query: 'query GetBooks { books { id title } }' }),
      signal: controller.signal,
    })
      .then((r) => r.json())
      .then((json) => setState(json.errors ? { error: json.errors[0] } : { data: json.data }))
      .catch((error) => error.name !== 'AbortError' && setState({ error }));
    return () => controller.abort();
  }, []);

  if (state.loading) return <p>Loading...</p>;
  if (state.error) return <p>{state.error.message}</p>;
  return <ul>{state.data.books.map((b) => <li key={b.id}>{b.title}</li>)}</ul>;
}

With Axios the request is shorter (axios.post('/graphql', { query, variables })), and response.data is the JSON body. Note one trap: Axios rejects on non-2xx statuses, but a GraphQL server often answers 200 with an errors array, so you still have to check response.data.errors yourself. Likewise, with fetch, response.ok only tells you about HTTP.

What you give up with the hand-written version: caching and de-duplication of identical requests, request cancellation done right, normalized updates after mutations, retries, polling and devtools. For a page with one or two queries, fetch is fine. When the same data appears on several screens, a library earns its size. The urql and TanStack Query (with a small fetcher) libraries sit in between.

Stand-in: the state machine behind the hooks

The stand-in has no React and no Apollo. It builds createQuery (a loading/data/error state machine with refetch) and createMutation (a function plus state, with onCompleted) over a fake GraphQL endpoint whose first request fails with a network error. It prints the states the component would render. The names mirror the hooks, but this is not Apollo's implementation.

Node.js The states inside useQuery and useMutation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first load ends in error, the retry goes through loading to data, and a mutation's result only appears after a refetch (here the simplest cache update). A failed mutation is kept on the mutation state, so the form can show a message beside the button. (In real Apollo the promise returned by the mutate function also rejects unless you pass an onError option, so wrap the call in try/catch as above.)

Bypassing, persisting and resetting the cache

fetchPolicy: 'no-cache' bypasses the cache for one query: the result is neither read from nor written to it. Use it for data that must always be fresh and is never shared. The cache normally lives in memory and disappears on reload; persisting it means saving it (for example to localStorage with the apollo3-cache-persist package) and restoring it at start-up so the app opens with data already on screen. Resetting is for logout: client.clearStore() empties the cache without refetching, while client.resetStore() also re-runs active queries. Always clear the cache when the user changes, or the next person may briefly see the previous user's data.

Normalized caching

When a result arrives, a normalized cache does not store it as one blob. It flattens the response into objects, each saved under a key made of __typename and id, with relationships stored as references to other keys:

TEXT
Query.books({"genre":"scifi"}) -> [ref Book:1, ref Book:2]
Book:1 -> { title: "Dune", author: ref Author:5 }
Author:5 -> { name: "Frank Herbert" }

Because every object exists once, an update to Author:5 is visible in every query that mentions that author. This is also why every object type you cache should expose an id field (see Caching and Performance and Schema Design Best Practices).

The stand-in below builds this store from a response. It is a few dozen lines, not a real client, but it works the same way in principle: normalize on the way in, rebuild the tree on the way out.

JS A stand-in normalized cache

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both books point to the single Author:5 entry, so renaming the author once changes it in every view. A real cache also tracks field arguments, expiry, missing fields and garbage collection.

Updating the cache after a mutation

When a mutation returns an object with an id, the cache merges it automatically, as in the stand-in above. Two cases need your help:

  • Created objects: a new todo is not in any list yet, so you either refetch the list or write the new item into the cached list yourself.
  • Deleted objects: remove them from the lists that reference them.

A read-only Apollo-style example of adding a created item to a cached list:

JavaScript
const [addTodo] = useMutation(ADD_TODO, {
  update(cache, { data }) {
    cache.modify({
      fields: {
        todos(existing = []) {
          const newRef = cache.writeFragment({
            data: data.addTodo.todo,
            fragment: gql`fragment NewTodo on Todo { id title done }`,
          });
          return [...existing, newRef];
        },
      },
    });
  },
});

If that feels heavy, refetching the list is also a legitimate choice for small lists.

Optimistic updates

An optimistic update shows the expected result immediately, before the server answers, and rolls it back if the request fails. It makes toggles, likes and edits feel instant. Libraries let you pass an optimisticResponse, which is a guess at the payload:

JavaScript
toggleTodo({
  variables: { id: "7" },
  optimisticResponse: {
    toggleTodo: { __typename: "ToggleTodoPayload", todo: { __typename: "Todo", id: "7", done: true } },
  },
});

Use it for actions that almost always succeed. For payments or anything with complicated validation, wait for the server. Typed error payloads from Modeling Errors make the rollback path clearer.

The next stand-in applies an optimistic change to a copy of a todo list, then either confirms or rolls back.

JS A stand-in optimistic update with rollback

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Code generation

A GraphQL schema is already a complete description of every type. Code generation reads that schema plus your query documents and writes TypeScript types (and sometimes typed hooks), so a typo in a field name becomes a compile error instead of a runtime surprise. The most common tool is GraphQL Code Generator. A typical read-only config:

YAML
# codegen.yml (shape only; plugin names depend on your setup)
schema: https://api.example.com/graphql
documents: "src/**/*.graphql"
generates:
  src/gql/types.ts:
    plugins:
      - typescript
      - typescript-operations

Given a document:

GRAPHQL
query GetBook($id: ID!) {
  book(id: $id) { id title }
}

the generator produces types in this spirit:

TypeScript
type GetBookQuery = {
  book: { id: string; title: string } | null;
};
type GetBookQueryVariables = { id: string };

Notice two details. The result type contains only the selected fields, so you cannot read book.author if you did not ask for it. And book is | null because the schema field is nullable (see Lists and Non-Null Types). Run codegen in CI so the types never go stale, and fail the build when a query no longer matches the schema.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a normalized cache use to store an object?

    Each object is stored once under a key like Author:5, and other objects hold references to it, so updates reach every query.
  2. 2. When is plain fetch a reasonable choice?

    GraphQL is just HTTP plus JSON. A library pays off when many components share cached data.
  3. 3. What is an optimistic update?

    It makes interfaces feel instant. The client keeps the old state so it can undo the change on failure.
  4. 4. Why is a generated query result type often smaller than the schema type?

    The result type mirrors the selection set, which is why reading an unrequested field is a compile error.

Summary

  • Plain fetch is enough for small needs; libraries add caching, states, optimism and types.
  • Apollo Client is feature-rich, urql is small and modular, Relay is strict and compiler-driven.
  • A normalized cache stores objects once, by __typename and id, so one update refreshes every view.
  • After mutations, merged objects update automatically; created and deleted items need cache edits or a refetch.
  • Optimistic updates trade certainty for speed and need a rollback path.
  • Codegen turns the schema and your documents into precise TypeScript types.
  • The cache and optimistic code here are stand-ins; the library snippets are read-only.

Next: Subscriptions, Live Updates and File Uploads.