State Management · Senior · Question 73 of 75

Why model async state as a discriminated union instead of separate fields?

type State =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: User[] }
  | { status: "error"; error: string };

Explanation

Libraries like TanStack Query expose the same idea via status. In your own reducers it removes defensive checks throughout the UI.

Further reading

Problem with a question

State Management · Senior · question 73

Test yourself

Take the State Management · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz