React JS Examples

We recommend using the new Apollo Client v3 @apollo/client this is the latest version of the Apollo GraphQL javascript client library. Previous versions of this library were called apollo-boost.

This library contains react hooks useQuery, useMutation, useLazyQuery, etc that make it easy to add GraphQL queries to your React app.

npm install @apollo/client graphql

Creating a quick simple client

import React from "react";
import { ApolloClient, ApolloProvider } from "@apollo/client";

const client = new ApolloClient({ uri: `/api/v1/graphql` });

Or a client with caching and automatic persisted queries

import {
} from "@apollo/client";
import { createPersistedQueryLink } from "@apollo/client/link/persisted-queries";
import { sha256 } from "crypto-hash";

let cache = await setupCache();
let httpLink = new HttpLink({ uri: "/api/v1/graphql" });
let link = createPersistedQueryLink({
  useGETForHashedQueries: true,

const client = new ApolloClient({

Use the client in components to query for data

In this example we create a component UserProfile that user’s name by his id and displays that on the page.

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

const UserProfile = { id } => {
  const query = gql`
    query getUser {
      user(id: $id) {

  const variables = { id };
  const { error, loading, data } = useQuery(query, { variables });

  if (loading) {
    return <p>Loading</p>;

  return <h1>{}</h1>

Use the client in components to post data back

In this example we create a component UpdateUserProfile displays a text input which when changed causes a mutation query to be trigger to update the users name in the backend database. You can also insert or delete in mutation. More complex mutations like bulk insert, or nested insert and updates are also supported. Nested inserts are create to create an entry and create or update a related entitiy in the same request.

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

const UpdateUserProfile = { id } => {
  const query = gql`
    mutation setUserName {
      user(id: $id, update: $data) {

  const [setUserName] = useMutation(query);

  const updateName = (e) => {
    let name =;
    let variables = { data: { name } };

    setUserName({ variables })

  return <input type="text" onChange={updateName}>