How to Implement Apollo Client in React

This article provides a straightforward, step-by-step guide on how to integrate Apollo Client into a React application. You will learn how to install the necessary packages, initialize the Apollo Client instance, wrap your React application with the provider, and execute your first GraphQL query using React hooks.

Step 1: Install Dependencies

To get started, you need to install Apollo Client and the core GraphQL library. Run the following command in your project terminal:

npm install @apollo/client graphql

Step 2: Initialize Apollo Client

Next, configure your Apollo Client instance. You need to specify the URL of your GraphQL server and configure a cache. Create a file named apollo-client.js (or .ts if using TypeScript) and add the following code:

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

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

export default client;

Step 3: Connect Apollo Client to React

To make Apollo Client available throughout your React component tree, wrap your application with the ApolloProvider component. This component acts similarly to React’s Context Provider.

Open your entry file (such as index.js or main.jsx) and configure it as follows:

import React from 'react';
import ReactDOM from 'react-dom/client';
import { ApolloProvider } from '@apollo/client';
import App from './App';
import client from './apollo-client';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  </React.StrictMode>
);

Step 4: Fetch Data with useQuery

With the provider set up, you can now query your GraphQL API from any component using the useQuery hook.

Define your GraphQL query using the gql template literal, and pass it to the hook:

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

// Define the GraphQL query
const GET_USERS = gql`
  query GetUsers {
    users {
      id
      name
      email
    }
  }
`;

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

  // Handle loading state
  if (loading) return <p>Loading users...</p>;

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

  // Render the fetched data
  return (
    <ul>
      {data.users.map((user) => (
        <li key={user.id}>
          <strong>{user.name}</strong> - {user.email}
        </li>
      ))}
    </ul>
  );
}

export default UserList;