All Resources
Library
GraphQLReactApollo
June 3, 2024

GraphQL Apollo Client

Type-safe GraphQL queries with Apollo Client and automatic caching.

Overview

Apollo Client is a production-ready GraphQL client for React. It provides caching, state management, and type safety out of the box.

Key Features

  • Automatic Caching: Smart normalized caching
  • Type Safety: Generate TypeScript types from schema
  • Reactive Variables: Client-side state management
  • Subscriptions: Real-time updates with WebSocket
  • DevTools: Browser extension for debugging

Quick Start

npm install @apollo/client graphql

Setup

import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client'

const client = new ApolloClient({
  link: new HttpLink({
    uri: 'https://api.example.com/graphql'
  }),
  cache: new InMemoryCache()
})

Query Example

import { gql, useQuery } from '@apollo/client'

const GET_USERS = gql`
  query GetUsers($first: Int!) {
    users(first: $first) {
      id
      name
      email
    }
  }
`

export function UserList() {
  const { data, loading, error } = useQuery(GET_USERS, {
    variables: { first: 10 }
  })

  if (loading) return <div>Loading...</div>
  if (error) return <div>Error: {error.message}</div>

  return (
    <ul>
      {data.users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  )
}

Mutations

const CREATE_USER = gql`
  mutation CreateUser($name: String!, $email: String!) {
    createUser(name: $name, email: $email) {
      id
      name
    }
  }
`

const [createUser] = useMutation(CREATE_USER)

await createUser({
  variables: { name: 'Alice', email: 'alice@example.com' }
})

Apollo Client handles query deduplication and request batching automatically.

Curated by

Shyam