Get started with Apollo Client

Set up Apollo Client and fetch GraphQL data with React


Hello! 👋 This short tutorial gets you up and running with Apollo Client.

For an introduction to the entire Apollo platform, check out Odyssey, Apollo's interactive learning platform.

Step 1: Setup

To start this tutorial, do one of the following:

  • Create a new React project locally with Vite, or

  • Create a new React sandbox on CodeSandbox.

Step 2: Install dependencies

Applications that use Apollo Client require two top-level dependencies:

  • @apollo/client: This single package contains virtually everything you need to set up Apollo Client. It includes the in-memory cache, local state management, error handling, and a React-based view layer.

  • graphql: This package provides logic for parsing GraphQL queries.

Run the following command to install both of these packages:

Bash
1npm install @apollo/client graphql

If you're using a React sandbox from CodeSandbox and you encounter a TypeError, try downgrading the version of the graphql package to 15.8.0 in the Dependencies panel. If you encounter a different error after downgrading, refresh the page.

Our example application will use the FlyBy GraphQL API from Apollo Odyssey's Voyage tutorial series. This API provides a list of intergalactic travel locations and details about those locations 👽

Step 3: Initialize ApolloClient

With our dependencies set up, we can now initialize an ApolloClient instance.

In main.jsx, let's first import the symbols we need from @apollo/client:

JavaScript
main.jsx
1import { ApolloClient, InMemoryCache, ApolloProvider, gql } from '@apollo/client';

Next we'll initialize ApolloClient, passing its constructor a configuration object with the uri and cache fields:

JavaScript
main.jsx
1const client = new ApolloClient({
2  uri: 'https://flyby-router-demo.herokuapp.com/',
3  cache: new InMemoryCache(),
4});
  • uri specifies the URL of our GraphQL server.

  • cache is an instance of InMemoryCache, which Apollo Client uses to cache query results after fetching them.

That's it! Our client is ready to start fetching data. Now before we start using Apollo Client with React, let's first try sending a query with plain JavaScript.

In the same main.jsx file, call client.query() with the query string (wrapped in the gql template literal) shown below:

JavaScript
main.jsx
1// const client = ...
2
3client
4  .query({
5    query: gql`
6      query GetLocations {
7        locations {
8          id
9          name
10          description
11          photo
12        }
13      }
14    `,
15  })
16  .then((result) => console.log(result));

Run this code, open your console, and inspect the result object. You should see a data property with locations attached, along with some other properties like loading and networkStatus. Nice!

Although executing GraphQL operations directly like this can be useful, Apollo Client really shines when it's integrated with a view layer like React. You can bind queries to your UI and update it automatically as new data is fetched.

Let's look at how that works!

Step 4: Connect your client to React

You connect Apollo Client to React with the ApolloProvider component. Similar to React's Context.Provider, ApolloProvider wraps your React app and places Apollo Client on the context, enabling you to access it from anywhere in your component tree.

In main.jsx, let's wrap our React app with an ApolloProvider. We suggest putting the ApolloProvider somewhere high in your app, above any component that might need to access GraphQL data.

JavaScript
main.jsx
1import React from 'react';
2import * as ReactDOM from 'react-dom/client';
3import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
4import App from './App';
5
6const client = new ApolloClient({
7  uri: 'https://flyby-router-demo.herokuapp.com/',
8  cache: new InMemoryCache(),
9});
10
11// Supported in React 18+
12const root = ReactDOM.createRoot(document.getElementById('root'));
13
14root.render(
15  <ApolloProvider client={client}>
16    <App />
17  </ApolloProvider>,
18);

Step 5: Fetch data with useQuery

After your ApolloProvider is hooked up, you can start requesting data with useQuery. The useQuery hook is a React hook that shares GraphQL data with your UI.

Switching over to our App.jsx file, we'll start by replacing our existing file contents with the code snippet below:

JavaScript
App.jsx
1// Import everything needed to use the `useQuery` hook
2import { useQuery, gql } from '@apollo/client';
3
4export default function App() {
5  return (
6    <div>
7      <h2>My first Apollo app 🚀</h2>
8    </div>
9  );
10}

We can define the query we want to execute by wrapping it in the gql template literal:

JavaScript
App.jsx
1const GET_LOCATIONS = gql`
2  query GetLocations {
3    locations {
4      id
5      name
6      description
7      photo
8    }
9  }
10`;

Next, let's define a component named DisplayLocations that executes our GET_LOCATIONS query with the useQuery hook:

JavaScript
App.jsx
1function DisplayLocations() {
2  const { loading, error, data } = useQuery(GET_LOCATIONS);
3
4  if (loading) return <p>Loading...</p>;
5  if (error) return <p>Error : {error.message}</p>;
6
7  return data.locations.map(({ id, name, description, photo }) => (
8    <div key={id}>
9      <h3>{name}</h3>
10      <img width="400" height="250" alt="location-reference" src={`${photo}`} />
11      <br />
12      <b>About this location:</b>
13      <p>{description}</p>
14      <br />
15    </div>
16  ));
17}

Whenever this component renders, the useQuery hook automatically executes our query and returns a result object containing loading, error, and data properties:

  • Apollo Client automatically tracks a query's loading and error states, which are reflected in the loading and error properties.

  • When the result of your query comes back, it's attached to the data property.

Finally, we'll add DisplayLocations to our existing component tree:

JavaScript
App.jsx
1export default function App() {
2  return (
3    <div>
4      <h2>My first Apollo app 🚀</h2>
5      <br/>
6      <DisplayLocations />
7    </div>
8  );
9}

When your app reloads, you should briefly see a loading indicator, followed by a list of locations and details about those locations! If you don't, you can compare your code against the completed app on CodeSandbox.

Congrats, you just made your first component that renders with GraphQL data from Apollo Client! 🎉 Now you can try building more components that use useQuery and experiment with the concepts you just learned.

Next steps

Now that you've learned how to fetch data with Apollo Client, you're ready to dive deeper into creating more complex queries and mutations. After this section, we recommend moving on to:

  • Queries: Learn how to fetch queries with arguments and dive deeper into configuration options. For a full list of options, check out the API reference for useQuery.

  • Mutations: Learn how to update data with mutations and when you'll need to update the Apollo cache. For a full list of options, check out the API reference for useMutation.

  • Apollo Client API: Sometimes, you'll need to access the client directly like we did in our plain JavaScript example above. Visit the API reference for a full list of options.

Feedback

Edit on GitHub

Forums