Blog>
Snippets

Setting up Apollo Client with React

Demonstrate how to set up Apollo Client in a React project for connecting with a GraphQL API, including the ApolloProvider.
import React from 'react';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
import App from './App';
First, we import React, the necessary modules from Apollo Client, and the App component. ApolloClient and InMemoryCache are used to create the Apollo Client instance. ApolloProvider is a React component that provides the Apollo Client instance to the React component tree.
const client = new ApolloClient({
  uri: 'YOUR_GRAPHQL_API_ENDPOINT',
  cache: new InMemoryCache()
});
Then, we instantiate Apollo Client by creating a new client instance. Replace 'YOUR_GRAPHQL_API_ENDPOINT' with your actual GraphQL API endpoint. The InMemoryCache instance enables Apollo Client to cache query results.
const Root = () => (
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);
Next, we define a Root component that wraps the App component with ApolloProvider. The ApolloProvider component is passed the Apollo Client instance as a prop, thereby providing Apollo Client's functionality to the entire app.
export default Root;
Finally, we export the Root component so it can be used as the entry point of the application.