Skip to content

Apollo Client

Apollo Client is a comprehensive GraphQL client for JavaScript, designed to manage data fetching, caching, and state management in modern applications. It integrates seamlessly with frameworks like React, Vue, Angular, and more.


Why Use Apollo Client?

✅ Simplifies GraphQL queries and mutations in your frontend
✅ Automatically caches responses to reduce network calls
✅ Supports pagination, optimistic UI, and real-time updates
✅ Integrates with popular UI frameworks and state management tools


Installation

React Example

npm install @apollo/client graphql

Setting Up Apollo Client

// src/apolloClient.js
import { ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
  uri: "https://your-graphql-endpoint.com/graphql",
  cache: new InMemoryCache(),
});

export default client;

Wrap your app with the Apollo provider:

// src/index.js
import React from "react";
import ReactDOM from "react-dom";
import { ApolloProvider } from "@apollo/client";
import App from "./App";
import client from "./apolloClient";

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById("root")
);

Basic Query Example

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

const GET_USERS = gql`
  query GetUsers {
    users {
      id
      name
    }
  }
`;

function UserList() {
  const { loading, error, data } = useQuery(GET_USERS);

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

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

Mutations Example

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

const CREATE_USER = gql`
  mutation CreateUser($input: CreateUserInput!) {
    createUser(input: $input) {
      id
      name
    }
  }
`;

function AddUser() {
  const [createUser, { data, loading }] = useMutation(CREATE_USER);

  const handleSubmit = () => {
    createUser({
      variables: {
        input: { name: "Alice", email: "alice@example.com" },
      },
    });
  };

  return (
    <div>
      <button onClick={handleSubmit}>Add User</button>
      {loading && <p>Creating user...</p>}
      {data && <p>Created: {data.createUser.name}</p>}
    </div>
  );
}

Apollo DevTools

Install the Apollo Client DevTools extension to:

  • Inspect GraphQL queries and cache
  • Monitor network requests
  • Debug and explore schema

Advanced Features

  • Pagination with fetchMore or relay-style cursors
  • Optimistic UI updates
  • Local state management with reactive variables
  • Subscription support with WebSocket links
  • Fragment caching and updates

Resources


Summary

Apollo Client is a full-featured GraphQL client that simplifies frontend data management with powerful tooling, intelligent caching, and first-class integration with your UI framework.