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.

published: reading time: 7 min read author: Geek Workbench
Quick Summary

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 ProfileState to 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 status when 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

1. What is a discriminated union?
It is a union of object types sharing a literal field, such as status. Checking that field narrows the value to the matching shape.
2. Why can a union be safer than two booleans for request state?
A union allows one request phase at a time. Two booleans can represent loading and error together, even when that combination makes no sense for the UI.
3. How does an exhaustive check help when adding a state?
A never check makes an unhandled variant a type error. Adding a status points you to switches that need another branch.
4. What is a literal union type?
It restricts a value to a set of exact literals.
  • "light" | "dark" accepts those two strings.
  • Other strings such as "blue" are rejected.
5. What does narrowing change inside a branch?
A check removes union alternatives that cannot satisfy the condition.
  • After checking status === "success", success fields are available.
  • Fields from other variants remain unavailable.
6. Why keep payload fields on only the relevant variant?
It makes the type reflect which data exists for each state.
  • A loading state need not carry a success result.
  • Checking the discriminant proves when a payload can be read.
7. When are separate booleans appropriate?
Use them for independent conditions that may be true at the same time.
  • A panel can be open while a hint is dismissed.
  • Use one state union for mutually exclusive request phases.
8. What is the never type useful for in a switch?
It represents a value that cannot exist after every union case has been handled.
  • Pass the remaining value to an assertNever helper.
  • A newly added variant then triggers a compile-time error.
9. Can a type assertion validate a stored state?
No. An assertion only tells TypeScript to trust the code.
  • Parse and validate values read from storage.
  • Construct valid variants through checked application logic.
10. Why should status spellings stay consistent?
Each tag string identifies a distinct union member.
  • "success" and "loaded" are not interchangeable.
  • A shared literal spelling keeps checks and constructed values aligned.

Further Reading

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.

#react #typescript #accessibility

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.

#react #typescript #state-management

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.

#react #typescript #testing