Add apollo-client to a React project

Reading Time: < 1 minute


Set up Apollo Client for React

  • npm install apollo/client and graphql
npm install @apollo/client graphql
  • Create client.tsx file to store configuration of apollo-client react
  • import ApolloClient, InMemoryCache and HttpLink from ‘@apollo/client’
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
  • Initialize and export an instance of ApolloClient
const uri = '';
const link = new HttpLink({ uri });

const client = new ApolloClient({
    cache: new InMemoryCache(),

export default client;
  • Test client instance in client.tsx by executing a GraphQL query
  • Create a new folder named graphql and add get-languages.tsx in it
  • graphql/get-languages.tsx defines a GraphQL query that returns countries where official language is English.

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

export const GET_LANGUAGES = gql`
    query getLanguages {
        languages: Language(
            filter: { name_in: ["English"] },   
            orderBy: [name_asc]) {
                id: _id
                countries {
                    id: _id
                    flag {
  • Verify Apollo client can retrieve the results of GET_LANGUAGES and output to console
In client.tsx

import { GET_LANGUAGES } from './graphql/queries';


Connect Apollo Client to React

  • Import ApolloProvider component and client instance to App.tsx. The client instance is initialized and exported from client.tsx
  • Wrap ApolloProvider around top level element in App function
import { ApolloProvider } from "@apollo/client";
import client from './client';

const App = () => {
  return (
    <ApolloProvider client={client}>
        <p>Hello World!</p>

ReactDOM.render(<App/>, document.getElementById('root'));
  • Up to this point, the application can take advantage of Apollo Client to execute queries and mutations on client side