GraphQL and React fit together for one reason: the client holds a normalized cache that behaves like a miniature database, and every component that asks for overlapping fields reads from it instead of the network. Teams that treat the library as a fetch wrapper end up refetching whole queries after every mutation, flashing loading states on screens that already have usable data, and debugging why one component shows stale content while its neighbor does not. Teams that understand the cache write fewer queries, get updates for free across distant parts of the tree, and treat the network as the exception rather than the rule.
âšī¸Identify entities by type and id
The cache stores objects keyed by their type name and id, and every list reference points at those records. That is why a mutation returning the updated fields refreshes every view of that record automatically, and why a query that forgets the id field leaves the cache unable to join anything.
Reading data with useQuery
The hook returns a small state machine: loading, error, data and a network status you can distinguish from a background refetch. The mistake almost every team makes once is collapsing those into a single boolean, which produces a spinner on every refetch of data already on screen.
import { gql, useQuery } from '@apollo/client';
const GET_TEAM = gql`
query GetTeam($id: ID!) {
team(id: $id) {
id
name
members {
id
role
user { id name avatarUrl }
}
openTasks {
id
title
priority
assignee { id name }
}
}
}
`;
export function TeamBoard({ teamId }) {
const { data, loading, error, refetch, networkStatus } = useQuery(GET_TEAM, {
variables: { id: teamId },
notifyOnNetworkStatusChange: true,
fetchPolicy: 'cache-and-network',
nextFetchPolicy: 'cache-first',
});
if (error) {
return (
<div role="alert">
<p>Could not load the team board.</p>
<button onClick={() => refetch()}>Try again</button>
</div>
);
}
if (loading && !data) {
return <BoardSkeleton />;
}
const isRefetching = networkStatus === 3;
return (
<div aria-busy={isRefetching}>
<h1>{data.team.name}</h1>
<MemberList members={data.team.members} />
<TaskList tasks={data.team.openTasks} />
</div>
);
}
The fetch policy choice is deliberate. cache-and-network gives an immediate paint from the cache followed by a freshness pass in the background, which suits a dashboard that must feel instant. Switching to cache-first for subsequent queries avoids the extra round trip while the screen is still open. And the skeleton renders only when there is no data at all, so a background refresh never replaces readable content with a spinner.
Writing without a refetch storm
Mutations update the cache through returned fields rather than through re-running queries. If the mutation payload includes the identity and the fields that changed, the cache patches those records and every subscribed component re-renders with the new values. Only when the mutation creates or deletes an entity does the list itself need attention.
import { gql, useMutation } from '@apollo/client';
const ASSIGN_TASK = gql`
mutation AssignTask($taskId: ID!, $userId: ID!) {
assignTask(taskId: $taskId, userId: $userId) {
id
assignee { id name }
status
}
}
`;
const GET_TEAM = gql`
query GetTeam($id: ID!) {
team(id: $id) {
id
openTasks { id title priority assignee { id name } }
}
}
`;
export function AssignMenu({ task, members }) {
const [assign, { loading }] = useMutation(ASSIGN_TASK, {
optimisticResponse: {
assignTask: {
__typename: 'Task',
id: task.id,
status: task.status,
assignee: { __typename: 'User', id: 'pending', name: 'Assigning...' },
},
},
update(cache, { data }) {
if (!data) return;
const updated = data.assignTask;
cache.modify({
id: cache.identify({ __typename: 'Task', id: task.id }),
fields: {
assignee(existing) {
return { __typename: 'User', id: updated.assignee.id };
},
},
});
},
onError(error) {
console.error('assignment failed', error);
},
});
return (
<select
value={task.assignee ? task.assignee.id : ''}
disabled={loading}
onChange={(e) => assign({ variables: { taskId: task.id, userId: e.target.value } })}
aria-label={`Assign ${task.title}`}
>
<option value="">Unassigned</option>
{members.map((m) => (
<option key={m.id} value={m.id}>{m.name}</option>
))}
</select>
);
}
Notice that no refetchQueries call appears. The record identity is enough, and avoiding the refetch keeps the rest of the board from flashing. refetchQueries remains the right tool when the mutation affects a computed aggregate the cache cannot derive, such as a count the server maintains, but it should be the exception you can justify rather than the default you paste.
Cache update strategies
Four approaches cover nearly every case, and choosing the cheapest one that is correct keeps mutation handlers short.
| Strategy | When it is correct | Cost | Typical use |
|---|---|---|---|
| Return updated fields | The mutation changes fields on an existing entity | None, the cache patches automatically | Renaming, reassigning, editing a profile |
| cache.writeQuery | The mutation changes a whole list the cache owns | Low, you rewrite one query result | Adding an item to a known list |
| cache.modify by id | Only one record changes and you know its identity | Low and surgical | Toggling a flag on a specific record |
| refetchQueries | The server computes something the client cannot | A network round trip | Aggregates, totals, permission-dependent lists |
| Cache eviction | The record should stop existing anywhere | Dropping all references to the entity | Deleting a comment or a file |
A useful rule of thumb is to reach for refetchQueries last. It is always correct and always the most expensive, and leaning on it hides cache modelling mistakes until the application grows a screen where the refetch target does not exist.
Loading, errors and partial results
GraphQL's error model is different from REST: a query can return both data and a list of errors, because one field resolver may fail while its siblings succeed. Treating any error as fatal throws away perfectly good content, so read the data first and surface the error next to the region that is missing.
export function ProjectSummary({ id }) {
const { data, error, loading } = useQuery(GET_PROJECT, { variables: { id } });
if (loading && !data) return <SummarySkeleton />;
return (
<section>
<h2>{data?.project?.name || 'Untitled project'}</h2>
{error && (
<p role="status" className="partial-error">
Live totals are unavailable right now, showing the last known values.
</p>
)}
<p>Budget spent: {data?.project?.budgetSpent || 'unknown'}</p>
<p>Open items: {data?.project?.openItemCount || 'unknown'}</p>
</section>
);
}
Partial rendering also changes how you design queries. Request the fields a screen needs and nothing more, split a large query into per-region queries each behind its own boundary so one slow resolver does not blank the page, and rely on the cache to deduplicate overlapping selections so the extra boundaries cost no extra requests. Error boundaries still matter for the cases where a component throws rather than returning partial data, so pair them with per-region queries instead of choosing one over the other. The result is a screen that fills in by importance rather than all at once or not at all.
Optimistic updates that roll back cleanly
Optimistic UI is a promise to the user: show the result now, and if the server disagrees, put everything back. The library performs the rollback for you when the mutation rejects, provided the optimistic response you supplied has the same shape as the real one. A mismatch is how you end up with a phantom row that no state variable owns.
Use it where the action is frequent, local and easily reversed: starring, liking, reordering a queue, moving a card between columns. Skip it where the outcome depends on server-side rules the client does not know, such as a balance check or a permission that may deny the action, because a rollback there feels like the application rejecting the user rather than the network.
Subscriptions and live updates
Once the cache is the source of truth, live data becomes another writer rather than a separate pipeline. A subscription delivers a payload in the same shape as a query result, and handing it to the cache with the same identify-and-modify logic updates every view of that record without polling. The practical decisions are connection management and reconnect behaviour, because a dropped socket is a matter of when rather than whether.
import { gql, useSubscription } from '@apollo/client';
const TASK_MOVED = gql`
subscription OnTaskMoved($boardId: ID!) {
taskMoved(boardId: $boardId) {
id
status
position
assignee { id name }
}
}
`;
export function useLiveBoard(boardId) {
const { data, error } = useSubscription(TASK_MOVED, { variables: { boardId } });
return { lastEvent: data?.taskMoved, disconnected: Boolean(error) };
}
Keep subscriptions narrow. A channel that streams an entire board produces a payload larger than the query it replaces and fights the user's own edits, so send the delta, let the cache apply it, and let the components re-render from normalized records. When the socket drops, fall back to a refetch of the affected query on reconnect so anything missed during the gap is repaired once rather than never.
Common Mistakes
Collapsing loading, error and refetch into a single boolean
Fix: Distinguish first load from background refresh so existing content is never replaced by a spinner.
Calling refetchQueries after every mutation because it is always correct
Fix: Return the updated fields or write to the cache by identity, and reserve refetching for server-computed values.
Omitting id fields from selections so records cannot be normalized
Fix: Select id on every entity, or the cache cannot join a mutation result to the list that shows it.
Building an optimistic response whose shape does not match the mutation payload
Fix: Mirror the real selection exactly so a failed request can roll back without leaving phantom data.
Key Takeaways
- The normalized cache is the integration point: identify records by type and id and views update together
- Distinguish first load from background refetch so the interface never hides usable data behind a spinner
- Choose the cheapest correct update: returned fields, then cache write or modify, then refetch as a last resort
- GraphQL can return data and errors together, so render what arrived and report the failure next to what is missing
- Optimistic updates are best for frequent, reversible actions, and rollback only works when the shape matches the server