You're viewing documentation for a version of this software that is in development. Switch to the latest stable version
/
Launch Graph Manager

Get started

Set up Apollo Client in your React app


Out of the box Apollo Client includes packages that we think are essential for building an Apollo app, like our in-memory cache, local state management, error handling, and a React based view layer.

This tutorial walks you through installing and configuring Apollo Client for your React app. If you're just getting started with GraphQL or the Apollo platform, we recommend first completing the full-stack tutorial.

Installation

First, let's install the Apollo Client package:

npm install @apollo/client

If you'd like to walk through this tutorial yourself, we recommend either running a new React project locally with create-react-app or creating a new React sandbox on CodeSandbox. For reference, we will be using this CodeSandbox as our GraphQL server for our sample app, which pulls exchange rate data from the Coinbase API. If you'd like to skip ahead and see the app we're about to build, you can view it on CodeSandbox.

Create a client

Great, now that you have all the dependencies you need, let's create your Apollo Client. The only thing you need to get started is the endpoint for your GraphQL server. If you don't pass in uri directly, it defaults to the /graphql endpoint on the same host your app is served from.

In our index.js file, let's import ApolloClient from @apollo/client and add the endpoint for our GraphQL server to the uri property of the client config object.

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

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: 'https://48p1r2roz4.sse.codesandbox.io',
  })
});

That's it! Now your client is ready to start fetching data. Before we show how to use Apollo Client with React, let's try sending a query with plain JavaScript first. In the same index.js file, try calling client.query(). Remember to first import the gql function for parsing your query string into a query document.

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

...

client
  .query({
    query: gql`
      {
        rates(currency: "USD") {
          currency
        }
      }
    `
  })
  .then(result => console.log(result));

Open up your console and inspect the result object. You should see a data property with rates attached, along with some other properties like loading and networkStatus. While you don't need React or another front-end framework just to fetch data with Apollo Client, our view layer integrations make it easier to bind your queries to your UI and reactively update your components with data. Let's learn how to use Apollo Client with React so we can start building query components.

Connect your client to React

To connect Apollo Client to React, you will need to use the ApolloProvider component. The ApolloProvider is similar to React's Context.Provider. It wraps your React app and places the client on the context, which allows you to access it from anywhere in your component tree.

In index.js, let's wrap our React app with an ApolloProvider. We suggest putting the ApolloProvider somewhere high in your app, above any places where you need to access GraphQL data. For example, it could be outside of your root route component if you're using React Router.

import React from 'react';
import { render } from 'react-dom';

import { ApolloProvider } from '@apollo/client';

const App = () => (
  <ApolloProvider client={client}>
    <div>
      <h2>My first Apollo app 🚀</h2>
    </div>
  </ApolloProvider>
);

render(<App />, document.getElementById('root'));

Request data

Once your ApolloProvider is hooked up, you're ready to start requesting data with the useQuery hook! useQuery is a hook that leverages the Hooks API to share GraphQL data with your UI.

First, pass your GraphQL query wrapped in the gql function into the useQuery hook. When your component renders and the useQuery hook runs, a result object will be returned containing loading, error, and data properties. Apollo Client tracks error and loading state for you, which will be reflected in the loading and error properties. Once the result of your query comes back, it will be attached to the data property.

Let's create an ExchangeRates component in index.js to see the useQuery hook in action!

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

const EXCHANGE_RATES = gql`
  {
    rates(currency: "USD") {
      currency
      rate
    }
  }
`;

function ExchangeRates() {
  const { loading, error, data } = useQuery(EXCHANGE_RATES);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return data.rates.map(({ currency, rate }) => (
    <div key={currency}>
      <p>
        {currency}: {rate}
      </p>
    </div>
  ));
}

Congrats, you just made your first useQuery based component! 🎉 If you render your ExchangeRates component within your App component from the previous example, you'll first see a loading indicator and then data on the page once it's ready. Apollo Client automatically caches this data when it comes back from the server, so you won't see a loading indicator if you run the same query twice.

If you'd like to play around with the app we just built, you can view it on CodeSandbox. Don't stop there! Try building more components that leverage useQuery and experimenting with the concepts you just learned.

If you'd like to explore further, here are more versions of the example app featuring different front-end libraries:

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 onto:

  • 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 components.
  • 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.
Edit on GitHub