How to Integrate GraphQL with React: A Step-by-Step Tutorial

GraphQL gives you precise control over the data your React app requests, eliminating over-fetching and under-fetching. The most common way to connect GraphQL with React is through Apollo Client, a powerful library that handles queries, mutations, and caching. This tutorial walks you through the essential steps to get GraphQL running in your React project.

First, install the required packages: npm install @apollo/client graphql. Then create an Apollo Client instance pointing to your GraphQL endpoint and wrap your app in the ApolloProvider component. This makes the client available to all components.

Article illustration

1. Setting Up Apollo Client

In your entry file (e.g., index.js), configure the client:

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

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

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

2. Writing and Executing Queries

Use the useQuery hook inside your components. Define your GraphQL query with the gql template literal tag:

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

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

function UsersList() {
  const { loading, error, data } = useQuery(GET_USERS);
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;
  return data.users.map(user => <div key={user.id}>{user.name}</div>);
}

3. Handling Mutations

Mutations modify data. Use useMutation for operations like adding or updating resources:

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

const ADD_USER = gql`
  mutation AddUser($name: String!, $email: String!) {
    addUser(name: $name, email: $email) { id name email }
  }
`;

function AddUserForm() {
  const [addUser, { data }] = useMutation(ADD_USER);
  const handleSubmit = (e) => {
    e.preventDefault();
    addUser({ variables: { name: 'New', email: 'new@test.com' } });
  };
  return <form onSubmit={handleSubmit}>...</form>;
}

4. Refetching and Caching

Apollo Client automatically caches query results. To refresh data after a mutation, use refetchQueries or update the cache manually with the update callback in useMutation. For example:

addUser({
  variables: { name, email },
  refetchQueries: [{ query: GET_USERS }]
});

Mastering these building blocks—setting up the client, running queries, executing mutations, and managing the cache—will enable you to build efficient, dynamic React applications powered by GraphQL. Start with a simple endpoint and gradually explore advanced features like subscriptions and pagination. Happy coding!

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *