Skip to content

Server state vs UI state

Working knowledgeConcept

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.

TodoList.jsx
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 />;
// ...
}

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

UI state and server state side by side
QuestionUI stateServer state
Who owns it?Your componentThe server; you hold a copy
Who else can change it?NobodyOther users, other tabs, jobs
Is your value correct?Always, by definitionOnly as of the last fetch
Getting itSynchronousAsync: loading, errors, retries
Who needs it?Usually one part of the screenOften many components at once
ExamplesOpen menu, selected tab, form draftTodos, 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.

One query key over time (TanStack Query behaviour)
Step 1 of 8
todos on the server
3 todos
query cache in the browser
Empty
requests sent
Empty
  • just changed
  • read from
  • held

The page loads. The server holds 3 todos; the browser has fetched nothing and its cache is empty.

nothing yet on screen

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.

useState + useEffect
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 />;
// ...
}
useQuery
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 filter from all to done quickly and the all response can land last, overwriting the right answer. The effect needs an ignore flag or an AbortController; 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 todos as null and the spinner spins forever.
  • Back and forth. Return to all and 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.

JavaScript
const queryClient = useQueryClient();
const addTodo = useMutation({
mutationFn: (text) =>
fetch('/todos', { method: 'POST', body: JSON.stringify({ text }) }),
onSuccess: () => {
// Marks every ['todos', ...] entry stale and refetches the ones on screen.
queryClient.invalidateQueries({ queryKey: ['todos'] });
},
});

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

UI stateuseState, URLYou own it, so store it plainly. Put it in the URL when a reload or a shared link should keep it.
Server stateQuery cacheA copy with an age. Let a cache keyed by the request hold it, share it and refresh it.
Derived valuesComputeCounts, filters and totals worked out from the other two. Calculate them in render; storing them creates a third copy to keep in sync.
Sorting some common values
ValueKindLives in
Is the add-todo dialog openUIuseState
The current filterUIuseState, or the URL if links should keep it
The text being typed in a new todoUI until saveduseState
The list of todosServerQuery cache, key ['todos', filter]
How many todos are doneDerivedComputed from the cached list
The signed-in userServerQuery 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.

08 Check yourself

Question

With TanStack Query, an entry for ['todos'] is stale. A new component that needs it mounts. What does that component show first?

Question

Two components call useQuery with the key ['me'] at the same time. How many requests are sent?

Question

After a successful POST /todos, what is the safest way to show the new todo?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?