HeadlinesBriefing favicon HeadlinesBriefing.com

Type-Safe React: Fix Invalid UI States

DEV Community •
×

React developers often ship bugs like showing loading spinners and error messages simultaneously. These aren't logic errors but state design errors. The root cause is "boolean soup"—using independent flags like `isLoading` and `isError` that allow invalid combinations.

A better approach uses discriminated unions to make invalid states impossible. Instead of four separate booleans creating 16 possible states (12 invalid), a single `status` property ensures only valid states exist. This pattern transforms state management across async data fetching, forms, and authentication.

TypeScript enforces exhaustive handling, turning the compiler into a refactoring assistant. The payoff is eliminating entire categories of UI bugs that previously required defensive checks.