Server state vs UI state
You fetch a list into useState and it works, until it shows yesterday’s data or two parts of the page disagree. The fix starts with seeing fetched data for what it is: a cache of someone else’s state, with an age, not state you own.
01 Two kinds of state in one component
Most React components hold two very different things in useState. Here, filter is something the user picked. todos is something the server said.
They look the same in code, but they behave differently. Nobody else can change filter. Anyone can change todos: another user, another tab, a background job. The moment the response arrives, todos starts going out of date, and nothing in this component will ever notice.
02 What makes server state different
| Question | UI state | Server state |
|---|---|---|
| Who owns it? | Your component | The server; you hold a copy |
| Who else can change it? | Nobody | Other users, other tabs, jobs |
| Is your value correct? | Always, by definition | Only as of the last fetch |
| Getting it | Synchronous | Async: loading, errors, retries |
| Who needs it? | Usually one part of the screen | Often many components at once |
| Examples | Open menu, selected tab, form draft | Todos, the current user, prices |
The third row is the important one. UI state is the truth. Server state is a cache of the truth, and every cache comes with the same questions: when is my copy too old, who refreshes it, and how do two readers share one copy?
03 Your copy is a cache, drawn
Libraries such as TanStack Query and SWR treat fetched data as exactly that. Each request is stored under a query key, and every component that asks for the same key shares one entry. The trace follows TanStack Query v5’s behaviour; the times are an example.
- just changed
- read from
- held
The page loads. The server holds 3 todos; the browser has fetched nothing and its cache is empty.
Two ideas carry the whole model. Staleness: an entry is fresh for staleTime, then stale, and stale entries are refetched on triggers such as mounting, window focus or reconnecting. Sharing: the key, not the component, owns the data, so the second reader costs nothing.
TanStack Query’s default staleTime is 0: data is stale the moment it arrives, and is refetched whenever a new component asks for it or the window regains focus. That surprises people who see a request on every tab switch. Raise staleTime for data that changes slowly.
04 What the useEffect version is missing
The hand-written version from the first section works on a good day. Here is the same component with a query library. The code is about the same size; what it handles is not.
function TodoList() {const [todos, setTodos] = useState(null);const [filter, setFilter] = useState('all');useEffect(() => {fetch(`/todos?filter=${filter}`).then((r) => r.json()).then(setTodos);}, [filter]);if (!todos) return <Spinner />;// ...}
function TodoList() {const [filter, setFilter] = useState('all');const { data: todos, isPending, error } = useQuery({queryKey: ['todos', filter],queryFn: () =>fetch(`/todos?filter=${filter}`).then((r) => r.json()),staleTime: 30_000,});if (isPending) return <Spinner />;// ...}
- Races. Switch
filterfromalltodonequickly and theallresponse can land last, overwriting the right answer. The effect needs an ignore flag or anAbortController; the query library keys each response, so a late one cannot land in the wrong place. - No sharing. A second component that needs todos fetches them again and holds its own copy, which can disagree with the first.
- No refresh. The data never updates until the component unmounts and mounts again.
- No errors. A failed request leaves
todosasnulland the spinner spins forever. - Back and forth. Return to
alland it fetches again with a spinner, though you saw that list a second ago. The cache would show it at once and refetch behind it.
05 After you change it, invalidate
When the user adds a todo, the tempting move is to push it into your local copy. That copy is still a guess about the server: it lacks the ID the server assigned, the order it sorted by, and anything another user added. Tell the cache instead that the entry is out of date, and let it ask the owner.
invalidateQueries matches by prefix, so ['todos'] covers ['todos', 'all'] and ['todos', 'done']. If the round trip is too slow to wait for, update the cache optimistically and still invalidate afterwards, so the server’s answer wins in the end.
06 Where each kind of state belongs
| Value | Kind | Lives in |
|---|---|---|
| Is the add-todo dialog open | UI | useState |
| The current filter | UI | useState, or the URL if links should keep it |
| The text being typed in a new todo | UI until saved | useState |
| The list of todos | Server | Query cache, key ['todos', filter] |
| How many todos are done | Derived | Computed from the cached list |
| The signed-in user | Server | Query cache, key ['me'] |
07 When server state goes wrong
const [list, setList] = useState(data);Copying query data into useStateuseState only uses its argument on the first render. When the cache refetches, data changes and list does not. Read data directly, and keep only your edits in state.queryKey: ['todos'] // fetches /todos?filter=…A key that leaves out an inputIf the request depends on filter but the key does not, every filter shares one entry and shows another filter’s list. Put every input of the request in the key.dispatch({ type: 'todosLoaded', todos })Fetched data in a global storePutting responses in a client store makes you write staleness, refetching and invalidation by hand, for every endpoint. Keep the store for UI state that is truly global.if (!data) return <Spinner />Treating refetching as loadingA background refetch keeps the old data on screen. Show a spinner only when there is no data yet (isPending); use isFetching for a small “updating” hint.todos.push(newTodo)Editing the cached object in placeThe cache hands every reader the same object. Mutating it changes what others see without telling React to re-render. Invalidate, or use setQueryData with a new array.