APP-26Recommended
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. The server stays the source of truth.
Examples
TypeScript 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,
});
}
Python example
@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)
HTML example
<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.
Related rules
- DAT-44 Name the source of truth in Data and databases
- APP-78 Return people to where they were on Back in Web app interface
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/app-ui/client-and-server-state/server-state-cache">Agent Wranglers web app interface playbook</a>. In code you write, add a comment next to it with the same link.