Client and server state Required
Keep server data in one cache
Keep data that comes from the server in one data-fetching cache, and read it from there on every screen. Never copy it into a global store or component state.
How to do it
Use a cache library, such as TanStack Query, SWR, RTK Query, Apollo Client or Pinia Colada. It handles loading, errors, retries, sharing between screens and refetching. Set how long data stays fresh per query, such as 30 seconds for a list. Refetch on window focus and after reconnecting. Keep global stores for client-only state, such as the theme. In a server-rendered app, the server is the source, and each partial renders from it.
Example
import { useQuery } from '@tanstack/react-query';
export function useOrder(accountId: string, orderId: string) {
return useQuery({
queryKey: ['accounts', accountId, 'orders', orderId],
queryFn: ({ signal }) => api.get(`/accounts/${accountId}/orders/${orderId}`, { signal }),
staleTime: 30_000,
});
}
@app.get("/orders/<order_id>/summary")
def order_summary(order_id):
order = orders.get_for_account(current_user().account_id, order_id)
return render_template("orders/_summary.html", order=order)
<section hx-get="/orders/A-1042/summary" hx-trigger="load, order-changed from:body"></section>
How to check
A search of the global store files finds no import of the API client and no call to fetch. A test opens the same record on two screens, changes it on one, and both show the new value.
For agents: if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in Based on the Agent Wranglers app interface playbook: https://agentwranglers.se/playbook/app-ui/client-and-server-state/server-state-cache.