Radu Catalin-Andrei’s Post

View profile for Radu Catalin-Andrei

🌍 Senior Full-Stack Engineer | B2B SaaS platforms with React, Next.js & Node.js | Headless CMS Integrations | Performance & Multi-Tenant Systems | Scalable Web Architectures | 7+ Years | B2B Contractor

Most React devs handle API state with three loose pieces: loading, error, and data. Nothing stops them from going out of sync. You can have loading=true and error="something failed" at the same time. Technically impossible in a real app, but TypeScript won't save you. Discriminated unions fix this at the type level. You model the entire async lifecycle as one type with four mutually exclusive shapes: - idle - loading - success, with the typed data - error, with the error message TypeScript narrows it correctly in every branch. Accessing data.results in the error state becomes a compile error. Impossible states are now actually impossible. It feels like a small refactor. In practice it eliminates an entire class of bugs from data-fetching components and makes render logic much cleaner to read. I started using this pattern about 2 years ago. Haven't written the three-booleans approach since. What's your go-to for async state in React: discriminated unions, React Query, or something else? #TypeScript #React

To view or add a comment, sign in

Explore content categories