Loading, Empty, Error, and Success States in React
Model async React UI states clearly with TypeScript, show empty results and retry actions, and prevent stale requests from replacing newer feedback.
Async screens need to distinguish waiting, results, no data, no matches, and failure. A discriminated union keeps state-specific data together, runtime validation checks the response, and effect cleanup cancels obsolete searches so stale results do not replace newer ones. The example includes an accessible retry action.
Loading, Empty, Error, and Success States in React
Introduction
A request-driven component needs more than a list of results. While data loads, users need feedback; when there are no matches, they need to know the search worked. If a request fails, they need a clear next step.
Represent those outcomes explicitly. A TypeScript union makes it harder to show an error and success result at the same time, or to forget the empty case.
This guide models the request lifecycle with explicit states and gives each state useful feedback and recovery actions.
Model the request states
Give every outcome its own tag, then render from that tag. This example’s API returns directorySize for the full user directory and users for the current query. A successful response with an empty directory means no data; an empty result with a non-empty directory means no matches.
import { useEffect, useState } from "react";
interface User {
id: string;
name: string;
}
interface SearchPayload {
directorySize: number;
users: User[];
}
type ResultsState =
| { status: "idle" }
| { status: "loading" }
| { status: "error"; message: string }
| { status: "empty"; kind: "no-data" | "no-matches" }
| { status: "success"; users: User[] };
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
typeof value.id === "string" &&
"name" in value &&
typeof value.name === "string"
);
}
function isSearchPayload(value: unknown): value is SearchPayload {
return (
typeof value === "object" &&
value !== null &&
"directorySize" in value &&
typeof value.directorySize === "number" &&
value.directorySize >= 0 &&
"users" in value &&
Array.isArray(value.users) &&
value.users.every(isUser)
);
}
function UserResults({
state,
onRetry,
}: {
state: ResultsState;
onRetry: () => void;
}) {
switch (state.status) {
case "idle":
return <p>Search for users to get started.</p>;
case "loading":
return (
<p role="status" aria-live="polite">
Searching users…
</p>
);
case "error":
return (
<div>
<p role="alert">{state.message}</p>
<button type="button" onClick={onRetry}>
Try again
</button>
</div>
);
case "empty":
return (
<p role="status" aria-live="polite">
{state.kind === "no-data"
? "No users have been added yet."
: "No users match your search."}
</p>
);
case "success":
return (
<>
<p role="status" aria-live="polite">
{state.users.length} {state.users.length === 1 ? "user" : "users"}{" "}
found.
</p>
<ul>
{state.users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</>
);
default: {
const unhandled: never = state;
return unhandled;
}
}
}
function UserSearch() {
const [query, setQuery] = useState("");
const [retry, setRetry] = useState(0);
const [state, setState] = useState<ResultsState>({ status: "idle" });
useEffect(() => {
const normalizedQuery = query.trim();
if (!normalizedQuery) {
setState({ status: "idle" });
return;
}
const controller = new AbortController();
let current = true;
setState({ status: "loading" });
async function loadUsers() {
try {
const response = await fetch(
`/api/users?q=${encodeURIComponent(normalizedQuery)}`,
{ signal: controller.signal },
);
if (!response.ok) throw new Error("Request failed");
const payload: unknown = await response.json();
if (!isSearchPayload(payload)) throw new Error("Unexpected response");
if (!current) return;
if (payload.users.length === 0) {
setState({
status: "empty",
kind: payload.directorySize === 0 ? "no-data" : "no-matches",
});
} else {
setState({ status: "success", users: payload.users });
}
} catch {
if (current && !controller.signal.aborted) {
setState({
status: "error",
message: "Could not load users. Try again.",
});
}
}
}
void loadUsers();
return () => {
current = false;
controller.abort();
};
}, [query, retry]);
return (
<>
<label htmlFor="user-search">Search users</label>
<input
id="user-search"
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
<UserResults
state={state}
onRetry={() => setRetry((attempt) => attempt + 1)}
/>
</>
);
}
directorySize counts all users before the query is applied. If the API does not provide that count, the UI cannot reliably distinguish “no data” from “no matches.” In that case, show one no-results message or add the count to the response.
When query changes, React cleans up the previous effect before running it again. Cleanup aborts the old fetch and marks its closure inactive. The current check blocks a late result from updating state, even if the request has already resolved. The abort can also stop work that is still in progress. See React’s useEffect reference and MDN’s AbortController guide.
Request-state flow
flowchart LR
A[Start request] --> B[Loading]
B --> C[Success with results]
B --> D[Empty success]
B --> E[Error]
E --> F[Retry]
F --> B
Trade-Off Table
| State | Show | Why it helps |
|---|---|---|
| Idle | A prompt or initial action | Makes clear that nothing has started |
| Loading | Progress text or indicator | Confirms the action is being handled |
| Empty | “No users yet” or “No matches” | Separates an empty directory from a filtered result |
| Error | A short message and retry action | Gives users a way forward |
| Success | The returned content | Shows data only after it is ready |
Use only the states a feature needs. A one-off action may need loading and error only; search results often need all five. Avoid saying “No data” while a request is still running.
Production Failure Scenarios
If code stores loading, error, and users in three unrelated state variables, it can render stale rows under a new error or show an empty message before the request finishes. A discriminated union gives each status one valid shape. On a query change, cancel the previous request and ignore its result; otherwise a slow first search can replace a newer one. Keep raw server errors out of the UI and log only the diagnostic detail the team needs.
Common Pitfalls / Anti-Patterns
- Render empty only after a successful response with zero results.
- Set the state to loading when a retry starts so the old error does not linger.
- Check
response.ok;fetchdoes not reject for HTTP errors such as 404. - Use a polite
statusmessage for progress and result counts; reservealertfor an important failure. - Test slow responses, retry after failure, empty results, and requests finishing out of order.
Observability Checklist
- Watch network failures and unexpected response shapes.
- Track loading duration, retries, and failures separately.
- Keep raw server details out of user-facing errors.
Security and Compliance Notes
Treat server data as untrusted input. Validate its shape before using it, render user text as text, and do not expose credentials or internal error details in the UI. TypeScript helps after validation; it cannot prove that a network response is safe.
When to Use / When NOT to Use
Model loading, success, empty, and error separately when a request changes the screen. A one-off action may need only pending and failed feedback. Do not infer success from an empty array before the request completes.
Next exercise
Change the search component to debounce input by 250 ms. Type two queries quickly, then make the first request slower than the second. Confirm that only the second result appears, that the loading message is announced, and that retry works after a failed request. Try both an empty directory and a non-empty directory with no matching users.
Interview Questions
An empty result is a completed request with no matches. Loading means the request has not finished. Showing separate states tells the user what happened and avoids a false no-results message.
Requests can finish in a different order from when they started. Abort the previous request when the query changes, and guard the state update so an obsolete response cannot replace the current results.
No. Types are checked at compile time. Treat decoded JSON as unknown and validate its shape before relying on it as application data.
Each variant can carry only the values valid for that state.
- Only success needs the user list.
- Only error needs an error message.
No. A response with an HTTP error status still resolves as a Response.
- Check
response.okbefore reading success data. - Move to an error state when the status is not successful.
Start the retry as a new effect run. Cleanup aborts the old fetch and marks its result stale.
- Only update state while the effect's active flag is true.
- Set loading state when the retry starts.
Use visible status text and accessible live-region roles where appropriate.
role="status"can announce progress.role="alert"can announce an important error.
After a successful request returns no users or no matches for the query.
- Use response metadata to distinguish an empty directory from a query with no matches.
- Do not confuse it with a request that is still loading.
- Do not use it to hide a request error.
It can expose internal details that do not help the user recover.
- Show a short safe message and a useful retry action.
- Keep diagnostic detail in privacy-safe logs.
It checks that external JSON actually matches the shape expected by the component.
- Use a type guard or schema before storing results as trusted data.
- Static TypeScript types do not inspect network responses.
Further Reading
- For validating and canceling a request, continue to fetching and typing API data.
- Model the status tag with TypeScript union types and narrowing.
- React state with useState explains setter updates for async UI.
- See React effects with useEffect for synchronization and cleanup.
- Test retries and empty results with component and interaction testing.
- React’s useEffect reference, MDN’s Using Fetch guide, and the AbortController reference cover the browser and React APIs.
Conclusion
Make each request outcome visible and keep impossible combinations out of state. A typed status union describes the UI, runtime validation checks the response, and effect cleanup keeps an older search from replacing newer feedback. Users can tell whether they are waiting, need to retry, have no matching users, or are searching an empty directory.
Category
Related Posts
Accessible React UI: Semantics, Labels, and Keyboard Use
Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.
Advanced React State: When Local State Stops Fitting
Learn when React state needs a reducer and context, when Redux Toolkit helps, and why server data often belongs in a query cache instead.
Testing React Components and User Interactions
Write behavior-first React tests with accessible roles, realistic user events, and async assertions while avoiding brittle checks of implementation details.