Paweł Piech

Modeling UI state with discriminated unions

Most frontend bugs I have fixed did not come from complex logic. They came from state that was not modeled well. A screen could be loading and show an old error at the same time. A button could be disabled for two reasons, and I could not tell which one.

Discriminated unions in TypeScript gave me a simple way to fix this. I do not use them everywhere, but on screens with more than one state, they changed how I work.

The old way

Early in my career I modeled a data screen like this:

const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const [data, setData] = useState<Alert[] | null>(null);
const [error, setError] = useState<Error | null>(null);

Four separate values. Each one can change on its own, so nothing stops the impossible combinations. The screen can be loading and have data. It can be idle with no data and no error. When a request fails after a success, old data stays on screen while the error appears. I then add more checks to hide it. The checks grow.

The idea

Instead of separate flags, I describe the states the screen can be in:

type AlertsState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "error"; error: Error }
  | { status: "success"; data: Alert[] };

Each variant carries only its own data. There is no data during loading. The error state always has an error. The success state always has data. The status field is the discriminant. TypeScript uses it to tell the variants apart.

The state becomes one value, and I move it from one status to another:

const [state, setState] = useState<AlertsState>({ status: "idle" });

setState({ status: "loading" });
setState({ status: "success", data: alerts });
setState({ status: "error", error });

Old data cannot stay on screen by accident. When I move to error, I replace the whole state. If I want to keep old data, I have to model that on purpose.

Rendering stays simple. I only check the state I need at that point:

if (state.status === "error") {
  return <ErrorBox error={state.error} />;
}

Inside this block, TypeScript knows the state is the error variant, so state.error exists. There is no optional chaining and no fallback to null. The same idea works for the other states. I check the status, return the part of the UI for it, and TypeScript gives me the data for that state.

Adding a state is easier too. I add the variant and run the type check. Code that reads a field the new state does not have fails, so I get a list of places to review. Before, adding a boolean meant searching for every use of the old flags and hoping I found them all.

What changed in my work

The biggest change was on screens that do several things at once. Take a table with filters, polling, and an export button. It starts with flags for loading, refreshing, exporting, and errors. It is hard to explain what the screen is doing at any moment. Some combinations are valid, some are not, and the UI does not know the difference.

With a union, the main state is idle, loading, ready, or error. Polling is a refreshing flag inside the ready state, because I want to keep the table on screen. Export has its own small state. Each part has a status, and each status carries the data it needs.

The result was less code. I deleted several conditions that only existed to hide one flag when another one was true. When I added an empty state, the type check showed the places where the empty case needed handling. The type system became a checklist.

Code reviews and tests became simpler too. Before, a common comment was: what happens if data is null here? With a union, that question moves into the type. If the type does not allow the case, the question disappears. Tests follow the states that exist, not every combination of flags. The list is short because the type is short.

When not to use it

I do not model everything this way. A menu that is open or closed is fine as a boolean. A union for two simple states can add noise. The rule I use is simple: if the screen has data, loading, empty, and error, or if some values only make sense together, a union is worth it. If the states are truly independent, keep them separate.

Good state modeling is not about fancy types. It is about making the wrong state impossible to write. Discriminated unions do that with plain TypeScript and no library. They made my components smaller, my bugs easier to find, and my code easier to explain to the next person. That is a lot for one status field.