π§ React GraphQL with Apollo Client β A Modern Data Layer
π§² Introduction β Why Use GraphQL in React?
Traditional REST APIs often lead to over-fetching or under-fetching data, especially in component-rich applications. Enter GraphQLβa flexible query language developed by Facebook, which lets the client control the shape of the data.
Apollo Client is the most popular GraphQL client for React. It offers caching, devtools, pagination, and state management, making it easy to consume GraphQL APIs in React apps.
π― In this guide, youβll learn:
- Why GraphQL + React is a powerful combo
- How to configure Apollo Client
- How to query, mutate, and cache data
- Best practices for schema and performance
βοΈ 1. Setup β Installing Apollo Client
π¦ Install Required Packages
npm install @apollo/client graphql
π§ Initialize Apollo Client
// src/apolloClient.js
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://your-graphql-endpoint.com/graphql',
cache: new InMemoryCache(),
});
export default client;
π 2. Providing Apollo to Your React App
// src/index.jsx
import ReactDOM from 'react-dom/client';
import { ApolloProvider } from '@apollo/client';
import App from './App';
import client from './apolloClient';
ReactDOM.createRoot(document.getElementById('root')).render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>
);
π₯ 3. Querying Data with useQuery
// src/components/UserList.jsx
import { gql, useQuery } from '@apollo/client';
const GET_USERS = gql`
query GetUsers {
users {
id
name
email
}
}
`;
function UserList() {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.users.map(user => (
<li key={user.id}>{user.name} - {user.email}</li>
))}
</ul>
);
}
πΉ Explanation:
gql
parses GraphQL query stringsuseQuery
handles fetching, loading, and error state automatically
βοΈ 4. Mutating Data with useMutation
// src/components/AddUserForm.jsx
import { gql, useMutation } from '@apollo/client';
import { useState } from 'react';
const ADD_USER = gql`
mutation AddUser($name: String!, $email: String!) {
addUser(name: $name, email: $email) {
id
name
email
}
}
`;
function AddUserForm() {
const [form, setForm] = useState({ name: '', email: '' });
const [addUser] = useMutation(ADD_USER);
const handleSubmit = (e) => {
e.preventDefault();
addUser({ variables: form });
setForm({ name: '', email: '' });
};
return (
<form onSubmit={handleSubmit}>
<input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
<input value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} />
<button type="submit">Add User</button>
</form>
);
}
πΉ Explanation:
useMutation
runs GraphQL mutations- Variables are passed using
variables
object - Apollo cache updates automatically (configurable)
π‘ Best Practices & Insights
π Best Practice
- Use
ApolloClient
‘sInMemoryCache
with field policies to normalize data and avoid refetching.
π‘ Tip
- Use
refetchQueries
or cache manipulation to update the UI after mutations.
β οΈ Pitfall
- Donβt forget to wrap your
<App />
inApolloProvider
. Without it, hooks likeuseQuery
will throw errors.
π Best Practice
- Separate GraphQL queries into a
graphql/
orqueries/
folder for maintainability.
π§± Apollo Client Features
Feature | Description |
---|---|
Cache Normalization | Stores entities uniquely to prevent redundancy |
DevTools Support | Chrome extension for debugging queries |
Error Handling | Graceful handling of network or GraphQL errors |
Query Batching | Combines multiple queries into one request |
Pagination Support | Cursor-based pagination out of the box |
π Use Cases & Real-World Integration
- π CMS Integration: Use GraphQL APIs like Contentful, GraphCMS
- π§βπ« E-learning: Manage courses, lessons, users with fine-grained queries
- π¦ E-commerce: Apollo Client for product filtering, cart logic, and order creation
π Summary β Recap & Next Steps
React + Apollo Client makes it effortless to integrate with flexible GraphQL APIs.
π Key Takeaways
- Use
ApolloProvider
to initialize GraphQL context - Query with
useQuery
, mutate withuseMutation
- Benefit from built-in caching, devtools, and schema flexibility
βοΈ Real-World Relevance:
GraphQL + Apollo is used by companies like GitHub, Shopify, and Airbnb to build dynamic, performant UIs.
β FAQ β React GraphQL with Apollo
β Can I use Apollo with REST APIs?
β
Apollo specializes in GraphQL, but tools like Apollo Link REST let you call REST endpoints.
β What is the difference between REST and GraphQL in React?
β
REST uses fixed endpoints; GraphQL uses one endpoint and lets clients define response shape.
β Can Apollo Client manage local state?
β
Yes! You can use Apollo for global and local state management using reactive variables.
β Is Apollo Client compatible with React 18?
β
Absolutely. Apollo hooks (useQuery
, useMutation
) work perfectly with React 18 features.
β How can I paginate results using Apollo?
β
Use fetchMore
, offset/limit
or cursor-based pagination patterns from your GraphQL schema.
Share Now :