GraphQL on the Frontend

Query exactly the data a screen needs with GraphQL, using clients like Apollo, urql or TanStack Query with codegen.

Intermediate · about 5 hours · difficulty 3/5

Learn first: Server State with TanStack Query

GraphQL is an API style where the client sends a query describing the exact fields it wants, and the server returns JSON in that shape from a single endpoint. It is popular at companies with many clients (web, mobile) sharing one API, and with platforms like GitHub and Shopify.

Concepts

  • Schema: the typed contract of types, fields and relations the server exposes.
  • Queries read data, mutations change it, subscriptions stream updates.
  • Variables keep queries static and reusable: query Product($id: ID!) { product(id: $id) { name price } }.
  • Fragments let components declare the fields they need, colocated with the component.

Clients

  • Apollo Client: full-featured with a normalised cache that updates every screen showing an entity after a mutation.
  • urql: lighter and extensible.
  • Relay: highly optimised and opinionated, used at Meta scale.
  • A plain fetch or TanStack Query with graphql-request works well for simple needs.

Type safety

Use GraphQL Code Generator (or gql.tada) to generate TypeScript types from the schema and your queries, so a renamed field breaks the build rather than production.

Pitfalls

Over-fetching through huge shared queries; cache normalisation surprises when objects lack an id; errors that arrive with HTTP 200 inside an errors array, which you must check.

Good enough to move on

You can write queries with variables and fragments, run them from React with one client, generate types and update the cache after a mutation.

Key concepts

  • Schema, types and fields
  • Queries, mutations and variables
  • Fragments and colocation
  • Apollo Client
  • urql and Relay
  • GraphQL Code Generator
  • Normalised caching

Mini project

Build a small GitHub profile viewer with the GitHub GraphQL API: typed queries via codegen, fragments per component and a mutation that stars a repository and updates the cache.

Check yourself

A GraphQL response has status 200 but the UI shows nothing. What should your client code check?

Free resources