
A Simple React + TypeScript Pattern to Replace Nested if/else
A Simple React + TypeScript Pattern to Replace Nested if/else When I started building React apps, I wrote many nested if/else blocks in components. It worked, but after a few weeks, the code became hard to read. Today I want to share a small pattern that helps a lot: use a status map object instead of long condition chains . This is beginner-friendly, and you can use it right away. The problem Imagine you load user data from an API. Your UI has 4 states: loading error empty success Many people write something like this: if ( isLoading ) { return < p > Loading... </ p > } else if ( isError ) { return < p > Something went wrong </ p > } else if ( users . length === 0 ) { return < p > No users yet </ p > } else { return < UserList users = { users } /> } This is okay at first. But it gets messy when states grow. A cleaner pattern: status map Create one status value, then map it to UI. type Status = ' loading ' | ' error ' | ' empty ' | ' success ' function UsersPanel ({ status , users , }:
Continue reading on Dev.to React
Opens in a new tab




