The ownership problem of server state
Revisiting Usable Query and the architecture of asynchronous data: who owns a response, what a query key identifies, and why rollback isn't an inverse.
Before joining NEX, I'd spent a considerable amount of time working with at
Audiomack. I particularly liked the relationship between endpoint definitions, subscriptions and the store. There was a predictable place for everything to exist.
At NEX, we used . I found myself repeatedly defining API calls and managing their associated state, so I built Usable Query, an attempt to reproduce some of the programming model I'd grown accustomed to.
Looking back, I suspect part of the problem was that I understood Redux Toolkit considerably better than I understood React Query.
The interesting question wasn't how to manage more state. It was whether I needed to own that state at all.
The cache is already a store
Consider a project editor that fetches a project from an API and copies the response into an application store.
const { data } = useQuery(projectOptions(id));
useEffect(() => {
if (data) projectStore.set(data);
}, [data]);
We've introduced two independently writable representations of the same resource.
What happens when the query refetches while the editor contains unsaved changes? Does the store receive the new response? Does the response overwrite the changes? Which representation should the rest of the application read?
We've accidentally introduced a synchronisation protocol without defining its rules.
React Query already provides cache storage, subscriptions and mechanisms for updating and observing data outside individual components.
queryClient.getQueryData(projectKey);
queryClient.setQueryData(projectKey, update);
queryClient.getQueryCache().subscribe(listener);
Moving data into another store doesn't inherently make it more accessible. It gives us another representation to maintain.
Centralise the contract, not the data
I still appreciate the endpoint-oriented architecture of Redux Toolkit. What I'd reconsider is how much infrastructure is necessary to achieve it.
Here's how I might define a resource today:
import { queryOptions } from "@tanstack/react-query";
export const projects = {
all: ["projects"] as const,
detail: (id: string) =>
queryOptions({
queryKey: ["projects", "detail", id],
queryFn: ({ signal }) =>
api.projects.get(id, { signal }),
}),
list: (filters: ProjectFilters) =>
queryOptions({
queryKey: ["projects", "list", filters],
queryFn: ({ signal }) =>
api.projects.list(filters, { signal }),
}),
};
The same definition can be consumed by a component, a route loader or a prefetch operation.
useQuery(projects.detail(id));
queryClient.prefetchQuery(projects.detail(id));
queryClient.getQueryData(
projects.detail(id).queryKey
);
We've centralised resource identity and fetching behaviour without introducing another owner of the response. That's what is for.
The distinction is important because a query key identifies a cached result, not necessarily an entity.
A project returned by a list query and the same project returned by a detail query can exist in separate cache entries.
Both React Query and fundamentally cache query results rather than automatically maintaining a single normalised record for every entity.
Normalisation can solve this duplication, but introduces its own requirements around entity relationships, list membership and ordering.
Rollback is not the inverse of every mutation
One of the more interesting problems in asynchronous state management appears when two overlap.
Suppose a project's name is initially A.
The first mutation changes it to B. Before that request completes, another mutation changes it to C.
The first request subsequently fails.
A conventional snapshot rollback might restore A, destroying the second mutation's optimistic update in the process.
The problem isn't necessarily the optimistic update. It's the assumption that the snapshot captured before a mutation remains an appropriate rollback target.
An alternative is to represent pending operations separately from the last confirmed state.
function materialise<T>(
confirmed: T,
pending: Array<(value: T) => T>
): T {
return pending.reduce(
(value, operation) => operation(value),
confirmed
);
}
If the first operation fails, remove it and recompute the visible state from the remaining operations.
This introduces considerably more explicit semantics. We now have to understand ordering, acknowledgements and how pending operations interact with newly confirmed server data.
For some applications, serialising mutations is simpler. For others, server-issued versions or conflict detection become necessary.
The architecture depends on the consistency guarantees the product requires.
When another store actually makes sense
An image editor is an interesting counterexample to the idea that all API-derived state should remain in a query cache.
An editor contains operations that haven't happened on the server yet. Selections, temporary layers, undo history and unsaved changes have their own lifecycles.
Those belong to the editing session.
I would initialise the session from a server snapshot, then treat the draft as independently owned state rather than continuously synchronising two interchangeable copies.
type EditingSession = {
baseVersion: string;
draft: Project;
dirty: boolean;
};
The query cache represents the latest known server state. The editing session represents the user's current intention. Saving is an explicit operation between them.
If the server changes while the session is dirty, the application can detect that conflict instead of silently overwriting either representation.
Looking back at Usable Query, I still think there was something useful about wanting a more predictable data-access architecture.
I would just be considerably more selective about which responsibilities I abstract.
Centralising how data is accessed doesn't require centralising everything that data becomes.
— Adenekan
