How to Update Apollo Client in React
Updating Apollo Client in your React application ensures you have access to the latest performance improvements, bug fixes, and features. This article provides a straightforward, step-by-step guide on how to safely upgrade Apollo Client, modify your project dependencies, update codebase imports, and clean up legacy packages.
Step 1: Install the Latest Versions
To begin the update process, you need to install the latest version
of the unified @apollo/client package along with
graphql, which is a required peer dependency. Run the
appropriate command for your package manager:
# Using npm
npm install @apollo/client graphql
# Using yarn
yarn add @apollo/client graphqlStep 2: Update Import Statements
If you are upgrading from Apollo Client v2 to v3 or v4, you must
migrate your imports. Older versions of Apollo required separate
packages for the client, cache, and links. All of these are now
consolidated into @apollo/client.
Locate and replace your old imports:
Old Imports (v2 and below):
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import { ApolloProvider } from 'react-apollo';
import { useQuery } from '@apollo/react-hooks';New Unified Imports:
import { ApolloClient, InMemoryCache, HttpLink, ApolloProvider, useQuery } from '@apollo/client';Step 3: Verify Client Initialization
Ensure your Apollo Client initialization uses the new consolidated imports. The basic setup remains highly readable and standardized:
import React from 'react';
import { createRoot } from 'react-dom/client';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
import App from './App';
const client = new ApolloClient({
uri: 'https://your-graphql-endpoint.com/graphql',
cache: new InMemoryCache(),
});
const root = createRoot(document.getElementById('root'));
root.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>
);Step 4: Remove Deprecated Packages
Once you have replaced all imports throughout your codebase,
uninstall the obsolete Apollo packages to keep your bundle size small
and your package.json clean.
# Using npm
npm uninstall apollo-boost react-apollo apollo-client apollo-cache-inmemory apollo-link-http @apollo/react-hooks
# Using yarn
yarn remove apollo-boost react-apollo apollo-client apollo-cache-inmemory apollo-link-http @apollo/react-hooksStep 5: Test and Verify
After completing the dependency changes: 1. Clear your package manager cache and reinstall node modules if you encounter resolution errors. 2. Run your local development server to check for runtime console warnings. 3. Execute your application’s test suite to verify that queries, mutations, and cache updates behave as expected under the updated client version.