Launch Apollo Studio

Get started with Apollo Client


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

For a more complete introduction to the entire Apollo platform, check out Odyssey, Apollo's new learning platform. You can also complete the full-stack tutorial.

1. Setup

To walk through this tutorial, we recommend you either:

Let's install the packages we need:

npm install @apollo/client graphql
  • @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.

We'll be using this CodeSandbox as the GraphQL server for our sample app, which pulls exchange rate data from the Coinbase API. You can also view the completed React app on CodeSandbox.

2. Initialize ApolloClient

Now that we have the dependencies we need, let's initialize an ApolloClient instance.

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

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

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

index.js
const client = new ApolloClient({
  uri: 'https://48p1r2roz4.sse.codesandbox.io',
  cache: new InMemoryCache()
});
  • 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 index.js file, call client.query() with the query string (wrapped in the gql template literal) shown below:

index.js
// const client = ...

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

Run this code, open 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. 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!

3. 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, which enables 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 component that might need to access GraphQL data.

index.js
import React from 'react';
import { render } from 'react-dom';
import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  useQuery,
  gql
} from "@apollo/client";

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

function App() {
  return (
    <div>
      <h2>My first Apollo app 🚀</h2>
    </div>
  );
}

render(
  <ApolloProvider client={client}>    <App />  </ApolloProvider>,  document.getElementById('root'),
);

4. Fetch data with useQuery

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

Still in index.js, let's first define the query we want to execute by wrapping it in the gql template literal:

index.js
const EXCHANGE_RATES = gql`
  query GetExchangeRates {
    rates(currency: "USD") {
      currency
      rate
    }
  }
`;

Next, let's define a component called ExchangeRates that executes our GetExchangeRates query with the useQuery hook:

index.js
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>
  ));
}

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

  • Apollo Client tracks a query's error and loading state for you, 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 ExchangeRates to our existing component tree:

index.js
function App() {
  return (
    <div>
      <h2>My first Apollo app 🚀</h2>
      <ExchangeRates />    </div>
  );
}

When your app reloads, you should briefly see a loading indicator, followed by a list of exchange rates! 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.
Edit on GitHub