Union Types and Narrowing for React UI States
Learn how TypeScript union types model React loading, success, and error states, with discriminated unions, safe narrowing, and practical failure handling.
Union types make mutually exclusive UI states explicit, and a discriminant such as `status` tells TypeScript which fields are safe to read. This post applies tagged unions to React request states, shows an exhaustive `never` check, and compares unions with independent booleans. It also explains how to validate external data before using it as a state value.
Union Types and Narrowing for React UI States
Introduction
A React component can be loading, show returned data, or show an error. With unrelated booleans, impossible combinations can slip in, such as isLoading === true while an error message is also shown.
Union types limit a value to a small set of shapes. TypeScript narrows the union as your code checks which shape it has.
This guide models request states as tagged unions, narrows each case safely, and uses exhaustive checks to catch changes.
Here is a profile request type with one tag per valid state:
type ProfileState =
| { status: "loading" }
| { status: "success"; name: string }
| { status: "error"; message: string };
Render each state in React
function Profile({ state }: { state: ProfileState }) {
switch (state.status) {
case "loading":
return <p>Loading profile…</p>;
case "success":
return <h1>{state.name}</h1>;
case "error":
return <p role="alert">{state.message}</p>;
}
}
The success branch can read state.name; the loading branch cannot. This prevents UI code from reaching for data before it exists.
An exhaustive check can make future changes safer. If another variant is added later, the compiler points to places that still need handling:
function assertNever(value: never): never {
throw new Error(`Unhandled state: ${JSON.stringify(value)}`);
}
Add default: return assertNever(state); after the cases. If a new status is added, TypeScript reports the unhandled case.
stateDiagram-v2
[*] --> Loading
Loading --> Success: request resolves
Loading --> Error: request rejects
Error --> Loading: retry
Success --> [*]
When to Use / When NOT to Use
Use a discriminated union when states are mutually exclusive or each state carries different data, such as a request that is loading, successful, or failed. Separate booleans fit independent choices, such as whether a panel is open and a hint is dismissed.
Do not force a union onto unrelated flags that can be true at the same time. If options are independent, keep their types separate.
Trade-Off Table
| Approach | Good fit | Trade-off |
|---|---|---|
Separate booleans (loading, hasError) |
A tiny independent toggle | Allows contradictory combinations as features grow |
| One status union | Mutually exclusive request states | More variants to name and handle |
| Discriminated union with payloads | States carry different data | Requires checking the tag before reading payload fields |
Production Failure Scenarios
Suppose a profile screen sets error after a failed request but forgets to clear loading. The spinner and error can appear together, and a retry may preserve the old message. A discriminated union makes that combination impossible: replace the state with { status: "loading" } or { status: "error", message }. On retry, enter loading and clear stale data in the same transition.
If a user switches profiles quickly, a slow response for the first profile can arrive last and replace the newer result. Abort the previous request or ignore its response before updating state, so old data cannot overwrite the active request’s state.
Common Pitfalls / Anti-Patterns
- Keep tag values consistent:
"success"and"loaded"are different variants. - Avoid optional fields on one loose object when a field belongs to only one state.
- Do not use
as ProfileStateto silence a missing case; validate or construct the variant.
Observability Checklist
- Record request status and a request ID so a failure can be matched to its UI state.
- Track whether a retry started and whether it resolved or failed.
- Keep sensitive response data out of logs.
- Compare the visible state with the latest request when diagnosing stale feedback.
Security and Compliance Notes
Treat API, URL, and local storage values as untrusted. TypeScript annotations do not validate runtime input. Check external data before using it; do not cast arbitrary JSON to ProfileState.
Quick Recap Checklist
- List the states the component can actually be in.
- Use a discriminant such as
statuswhen the states are mutually exclusive. - Narrow before reading fields that belong to one variant.
- Add an exhaustive check when new states should force code updates.
- Validate external data at runtime.
Interview Questions
status. Checking that field narrows the value to the matching shape.
never check makes an unhandled variant a type error. Adding a status points you to switches that need another branch.
"light" | "dark"accepts those two strings.- Other strings such as
"blue"are rejected.
- After checking
status === "success", success fields are available. - Fields from other variants remain unavailable.
- A loading state need not carry a success result.
- Checking the discriminant proves when a payload can be read.
- A panel can be open while a hint is dismissed.
- Use one state union for mutually exclusive request phases.
- Pass the remaining value to an
assertNeverhelper. - A newly added variant then triggers a compile-time error.
- Parse and validate values read from storage.
- Construct valid variants through checked application logic.
"success"and"loaded"are not interchangeable.- A shared literal spelling keeps checks and constructed values aligned.
Further Reading
- Type Inference and Annotations explains how TypeScript checks values and component boundaries.
- For related object shapes, read Objects, Arrays, and Interfaces.
- The React post on loading and error states applies explicit states to async UI.
- The TypeScript Handbook covers narrowing and checking union members.
- For React-specific examples, see the official React TypeScript guide.
Conclusion
Name the states your component can enter. A tagged union keeps each state with its data, narrowing makes rendering safer, and exhaustive checks catch forgotten branches. This small habit prevents confusing loading and error screens as a component grows.
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.