Getting Started With Apollo Client in Your React App

Adhithi Ravichandran
6 min readDec 15, 2021

--

Hi folks! It’s been a while since I have written a blog post. Hope everyone is doing well. Today I wanted to write about how to integrate Apollo Client, to consume a GraphQL API, from your React app. If you haven’t heard of Apollo for GraphQL, definitely check out their official docs for more information.

In our previous blog posts, we have discussed GraphQL. A quick summary on what GraphQL is:

GraphQL is a query language for APIs. It gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

What is Apollo Client?

Apollo Client, leverages the power of a GraphQL API to handle data fetching and management for you. Here is the architecture diagram to visualize how the Apollo Client works.

Apollo Client Architecture Diagram by Adhithi Ravichandran

Apollo Client is UI framework agnostic, which is super beneficial. You could use it with Angular, Vue, React or even native iOS and Android applications. The frontend application sends the GraphQL query to the Apollo Client, which processes the query and requests data from the GraphQL server. Note that the Apollo Client is agnostic of your GraphQL server’s technology. It is compatible across any build setup and GraphQL API.

The GraphQL server then sends the data response back to the Apollo Client. Which then normalizes and stores the data. The frontend application receives the UI updates. Apollo Client basically does some of the hard lifting work for the frontend application. It also provides intelligent caching out of the box.

Integrate Apollo Client

Alright, let’s get started with integrating Apollo Client within an existing React app.

Installation

The very first step is to install the following packages.

npm install @apollo/client graphql

apollo/client: Contains everything you need to setup Apollo Client (Version 3.0)

graphql: Provides logic for parsing GraphQL queries.

Imports

In the root of your app, which is usually index.js or App.js, let’s get the imports ready.

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

Import the symbols from the @apollo/client package directly.

Create Apollo Client

Next, initialize the Apollo Client within the app.

const client = new ApolloClient({
uri: ”https://my-example-url.com”, // Your running GraphQL server URL
cache: new InMemoryCache()
});

Within the root of your app, initialize an instance of the Apollo Client as shown above and provide it the GraphQL server URL. This can also be a local schema path.

Connect Apollo Client to React with Apollo Provider

The next step is to connect the Apollo Client to React with the Apollo Provider component. It wraps the React app and places the client on the context. This allows access to the Apollo Client from all the components within the app. Wrap the provider within the root of your application.

<ApolloProvider client = {client}>
<App />
</ApolloProvider>

Consume GraphQL API and Execute Queries

Perfect! The initial setup work is done. Now we are ready to actually consume the GraphQL API and request data using GraphQL queries. I am going to use a sample application that displays session information for a conference. In this example, we are going to display conference sessions, by executing queries to the GraphQL API.

You can integrate Apollo Client into any React project and use it along with an existing GraphQL server. If you would like, you can also follow along using my repository: Consuming GraphQL using Apollo. The GraphQL server is already configured in this sample project. And we are only focusing on setting up the client.

useQuery Hook

Queries provides clients the power to ask for exactly what they need and nothing more.

The useQuery is a React hook, which is the API for executing queries in an Apollo application.

First we write the GraphQL query that we want to execute, using the gql symbol. Below is the query, that queries for the fields we want to display on the conference sessions page.

const ALL_SESSIONS = gql`
query sessions {
sessions {
id
title
startsAt
day
room
level
speakers {
id
name
}
}
}`;

Now within our component, we are ready to execute the query that has been defined above.

const { loading, error, data } = useQuery(ALL_SESSIONS);

The useQuery hook returns the loading and error states that are tracked by the Apollo Client. This will help the frontend component code for loading and error states to display to the user. When the result of the query comes back from the GraphQL Server, the data property is populated. The data property contains the json response from the GraphQL API.

Let’s add the hook to a component, this will ensure that when the component renders, the useQuery hook is executed. The AllSessionList component renders the sessions when the data is returned after executing the query. The loading sessions message is displayed briefly, until the data is returned.

function AllSessionList() {
const { loading, error, data } = useQuery(ALL_SESSIONS);
if (loading) return <p>Loading Sessions..</p>; if (error) return <p>Error loading sessions!</p>; return data.sessions.map((session) => (
<SessionItem
key={session.id}
session={{
...session,
}}
/>
));
}

Perfect! We wired up Apollo Client within our React app, and successfully executed a query.

Arguments in Queries

In our previous query, we simply queried for all the sessions and specific fields for the sessions. What if we wanted to filter the resulting data? What if we want to filter the sessions by the day? The user could click on a button, and want to see sessions for just a specific day.

Good news is this can be done using arguments in GraphQL.

We can pass arguments to fields to filter resulting data. Every field and nested object can get its own set of arguments.

We can enhance our previous query to filter by the day as follows.

const WEDNESDAY_SESSIONS = gql`
query sessions {
sessions(day:"Wednesday") {
id
title
startsAt
day
room
level
speakers {
id
name
}
}
}`;

Now our query returns only sessions that are on Wednesday. Hooray!

Variables in Queries

That’s not all! The previous query only filters based on a specific argument. What if we want the arguments to the fields to be dynamic? In our case, the user should be able to filter based on any day of the conference, not just a specific day.

GraphQL uses variables to query for dynamic values.

We can modify the query to accept variable arguments as follows:

const SESSIONS = gql`
query sessions($day: String!) {
sessions(day: $day) {
id
title
startsAt
day
room
level
speakers {
id
name
}
}
}`;

The $ represents that the argument is a variable. We have also defined the type of the variable to be String!. This means that the variable cannot be null, and must be of type String. We can now pass the variables to the useQuery hook as shown in the example below:

const { loading, error, data } = useQuery(SESSIONS, {
variables: { day },
});

We pass variables as a configuration option to the hook. In our case we are passing the day as a variable. In addition, we can also pass multiple variables to the GraphQL query based on the client’s need.

Conclusion

Alright, that’s a wrap folks. In this post we learned about the Apollo Client to consume a GraphQL API. First we learned how to integrate the Apollo Client within a React application. Next, we executed a few queries using the useQuery hook. In the next post, we will learn more about how to execute mutations and how caching works within Apollo Client.

If you liked this post, don’t forget to share it with your network. You can follow me on twitter @AdhithiRavi for more updates.

--

--

Adhithi Ravichandran
Adhithi Ravichandran

Written by Adhithi Ravichandran

Software Consultant, Author, Speaker, React|Next.js|React Native |GraphQL|Cypress|Playwright Dev & Indian Classical Musician