Integrate GraphQL in React with Apollo Client—queries, mutations, caching, and when to choose GraphQL over REST.
GraphQL lets the client request exactly the data it needs. Here’s how to use it in React with Apollo Client.
GraphQL and React data fetching
Concepts
Schema and operations — The API exposes a schema; you send queries (read) and mutations (write). Each operation declares the fields it needs.
Apollo Client — Provides useQuery, useMutation, and a normalized cache. Handles loading and error state and can persist or prefetch.
Caching — Apollo normalizes results by __typename and id. Updates to the cache after mutations keep the UI in sync. Use cache policies or refetch when needed.
When to use GraphQL — Good when clients need flexible shapes, many related entities, or real-time (subscriptions). Overkill for simple CRUD or when the backend team isn’t committed.
API style preference (survey):
API style for frontend (%)
Setup
Install @apollo/client and graphql. Wrap the app in ApolloProvider with your client (HTTP link and optionally auth). Use useQuery in components; use useMutation for writes and update cache or refetch.
GraphQL in React in 100 seconds:
Takeaway
GraphQL fits when you need flexible, typed APIs and a strong client cache. Use Apollo’s hooks and cache well; avoid over-fetching or under-fetching by designing the schema with the UI in mind.