How To Use React With Apollo GraphQL

Quick answer: Wrap your React app in <ApolloProvider client={client}> and fetch GraphQL queries inside components using Apollo's useQuery hook, mapping the returned data into small presentational components like <Job />.

In this tutorial I'll teach you how to use React with Apollo GraphQL client. You'll learn how to query GraphQL server and render query results, by building a simple React application.

As a bonus, I'll explain to you an important software development principle which will help you to write higher quality code.

Demo Application Overview

We'll be building a simple React application that renders a list of jobs that require GraphQL knowledge. We'll get this list of jobs by querying a GraphQL server.

Let's take a look at how our app will work. The first screen will display a title and a button:

React Apollo GraphQL demo initial screen showing a Load GraphQL jobs button
Figure 1. Our application.

User will click the Load GraphQL jobs button and then the loading spinner will be rendered instead of the button:

Loading spinner displayed while Apollo Client fetches GraphQL jobs data
Figure 2. Our application.

Finally, we'll render the number of jobs and the list of jobs, displaying job title, company name and locations for each job:

List of GraphQL jobs showing job titles, company names, and locations
Figure 3. Our application.

Here you can play with the app and you can find the full source code in this GitHub repository.

Our application will be made of two React components:

  1. Jobs
  2. Job

Jobs component will render the app title, the button and the loading indicator, as well as a list of jobs. Each job will be rendered by the Job component.

Creating the Job Presentational Component

Let's create our Job component first:

import React from "react";

function getCitiesLabel(cities) {
  return cities.length > 1 ? "Cities" : "City";
}

function getCitiesList(cities) {
  return cities.map((city) => city.name).join(", ");
}

function Job(props) {
  return (
    <a
      href={props.job.applyUrl}
      className="list-group-item list-group-item-action"
    >
      <h3>{props.job.title}</h3>
      <div>
        <strong>Company:</strong> {props.job.company.name}
      </div>
      {props.job.cities.length > 0 && (
        <div>
          <strong>{getCitiesLabel(props.job.cities)}: </strong>
          {getCitiesList(props.job.cities)}
        </div>
      )}
    </a>
  );
}

export default Job;
Code snippet 1. Job.component.js

To be continued…