GraphQL with React
Apollo Client, queries, mutations, subscriptions, and caching strategies.
Overview
GraphQL provides a flexible query language for APIs with Apollo Client as the React implementation.
Key Concepts
- Apollo Client — GraphQL client with React hooks
- Queries — Fetch data with useQuery
- Mutations — Modify data with useMutation
- Subscriptions — Real-time updates with useSubscription
- Cache — Normalized cache with automatic updates
Code Examples
import { ApolloClient, InMemoryCache, gql, useQuery, useMutation } from '@apollo/client';
const GET_POSTS = gql`
query GetPosts($limit: Int) {
posts(limit: $limit) {
id
title
author { name }
}
}
`;
const CREATE_POST = gql`
mutation CreatePost($input: PostInput!) {
createPost(input: $input) {
id
title
}
}
`;
function PostList() {
const { loading, error, data } = useQuery(GET_POSTS, { variables: { limit: 10 } });
if (loading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;
return (
<ul>
{data.posts.map(post => (
<li key={post.id}>
<h3>{post.title}</h3>
<p>By {post.author.name}</p>
</li>
))}
</ul>
);
}
function CreatePostForm() {
const [createPost, { loading }] = useMutation(CREATE_POST, {
refetchQueries: [{ query: GET_POSTS }],
});
const handleSubmit = async (e) => {
e.preventDefault();
await createPost({ variables: { input: { title: e.target.title.value } } });
e.target.reset();
};
return (
<form onSubmit={handleSubmit}>
<input name="title" required />
<button type="submit" disabled={loading}>Create</button>
</form>
);
}
Practice
Build a real-time comment system with GraphQL subscriptions.