
Server Data Isn't Client State: Stop Hand-Rolling API Caches
- كاتب موثّق
- React 19
محتويات المقال
loading and error flags next to it. A support lead refunds an order, and her screen shows "refunded" because her handler patches the list. Her colleague has had the dashboard open since the morning. An hour later, his screen still says "paid", and he tells the customer the refund hasn't gone through. Nothing in his app knew the data had changed, because nothing ever asked the server again.
The common misconception
useState or a global store, add isLoading and error flags, and you're done. If two screens need it, move it to the store.
What actually happens
Client state is yours; server state is a copy
isOpen.
What a copy needs that useState doesn't give
A key. The cached data is the answer to a question, like "orders with status paid", so the cache needs one entry per question. Freshness. Something has to decide when the copy is out of date and fetch it again, ideally in the background while the old data stays on screen. Deduplication. When the header badge and the page ask the same question, they should share one request and one answer. Invalidation. After your own write, every cached answer it affects has to be refreshed. Lifetime. Answers nobody reads anymore should eventually be dropped.
import { useEffect, useState } from "react";export function OrdersPage({ status }: { status: string }) { const [orders, setOrders] = useState<Order[]>([]); const [loading, setLoading] = useState(true); const [error, setError] = useState<Error | null>(null); useEffect(() => { // Fetched once per status, then never refreshed setLoading(true); fetchOrders(status) .then(setOrders) .catch(setError) .finally(() => setLoading(false)); }, [status]); if (loading) return <Spinner />; if (error) return <ErrorView error={error} />; return <OrderList orders={orders} />;}// useQuery comes from @tanstack/react-queryexport function OrdersPage({ status }: { status: string }) { const { data, isPending, error } = useQuery({ queryKey: ["orders", status], queryFn: () => fetchOrders(status), }); if (isPending) return <Spinner />; if (error) return <ErrorView error={error} />; return <OrderList orders={data} />;}What a server-state cache does for you
queryKey names the question, so every component that asks ["orders", status] reads the same cache entry. TanStack Query's documented defaults then handle freshness: cached data counts as stale right away, and a stale query refetches in the background when a new component using it mounts, when the window regains focus, and when the network reconnects. Failed queries are retried 3 times with exponential backoff before the error reaches the UI, and queries nobody uses are garbage collected after 5 minutes.
queryClient.invalidateQueries({ queryKey: ["orders"] }) marks every query whose key starts with "orders" as stale and refetches the ones on screen. Nobody patches the list by hand.
useState, a reducer or a store | ||
How to apply it in your project
Sort your state into two piles List what's in your stores and useStatecalls. Anything filled from an API response, plus the loading and error flags around it, is server state.Choose one server-state tool Use your framework's data fetching if it has one, or a cache library. If you already use Redux Toolkit, RTK Query is in the same package. Give every query a key with its parameters Include everything the request depends on, like ["orders", status], so different questions never share an answer.Invalidate after writes After a mutation succeeds, invalidate the affected keys instead of editing cached lists by hand.
Key takeaways
Client state belongs to your app; server state is a copy of data that others change, and it starts aging on arrival. A copy needs keys, freshness, deduplication, invalidation and a lifetime; useStateand a loading flag give none.Server-state tools give you those as defaults, like refetching on focus and reconnect, retries and cleanup. Keep drafts, filters and toggles in client state; read server data from the cache, and invalidate it after writes.
التعليقات (0)