React · Lesson 4 of 15 · 4 min
Conditional Rendering & List Management
This is about showing you can write clean, predictable UI logic and explaining React's reconciliation process when asked.
After this, you'll be able to explain the trade-offs between different conditional rendering patterns and defend your choice of list keys in a code review or an interview. These are fundamental skills; getting them wrong is a red flag.
Choose the right tool for conditional UI
You have three main ways to render UI conditionally in JSX. Choosing the right one signals that you value code clarity.
-
Ternary operator (
? :): Use this for simple, inline if-else logic. It's concise for switching between two small expressions.function AuthStatus({ isLoggedIn }) { return isLoggedIn ? <p>Welcome back</p> : <p>Please log in</p>; } -
Logical AND (
&&): Use this to render an element only if a condition is true. If the condition is falsy, React renders nothing.function AdminDashboard({ isAdmin }) { return ( <div> <h2>Dashboard</h2> {isAdmin && <AdminPanel />} </div> ); }The trap: If the expression on the left of
&&is0, React will render the number0. For example,items.length && <Component />will render0ifitemsis an empty array. To avoid this, coerce the value to a boolean:!!items.length && <Component />. -
if/elsestatements: For complex logic, multiple conditions, or when you need to return entirely different component structures, use standardif/elseblocks before yourreturnstatement. This is more readable than a nested ternary.function DataDisplay({ isLoading, error, data }) { if (isLoading) { return <p>Loading...</p>; } if (error) { return <p>Error: {error.message}</p>; } // ... render data }
An interviewer asking "which is best?" is testing your judgment. The answer is about context. Ternaries are for conciseness with simple logic.
ifstatements are for readability with complex logic. Overusing either is a code smell.
Render lists with stable keys
To render a list of items from an array, you'll use Array.prototype.map. For each item in the array, you return a React element.
Every element in the returned array must have a unique key prop.
interface Product {
id: string; // Unique identifier for the product
name: string;
price: number;
}
function ProductList({ products }: { products: Product[] }) {
if (!products || products.length === 0) {
return <p>No products available.</p>;
}
return (
<ul>
{products.map((product) => (
// Use a stable, unique ID from your data as the key.
<li key={product.id}>
{product.name} - ${product.price.toFixed(2)}
</li>
))}
</ul>
);
}
The key tells React which item is which. It's a string or number that uniquely identifies an element among its siblings. This is how React's reconciliation algorithm efficiently determines what changed when the list is updated, reordered, or filtered. Without a stable identity, React has to work harder and can make mistakes.
Why using an index as a key is a bug
Using an array index as a key (<li key={index}>) is a common mistake that interviewers specifically look for. It seems to work for simple lists, but it breaks when the list's order can change.
React uses the key to match elements between the old and new trees. Imagine a list of two items: [{id: 'A'}, {id: 'B'}]. They render with key={0} and key={1}.
Now, you prepend a new item, [{id: 'C'}, {id: 'A'}, {id: 'B'}]. The new keys are 0, 1, and 2.
- React sees the old
key={0}and the newkey={0}. It assumes it's the same component and just updates its props from item 'A' to item 'C'. - It does the same for
key={1}, updating the component that was showing 'A' to now show 'B'. - It then creates a new component for
key={2}.
This is inefficient, but more importantly, it's incorrect. If your list items have their own state (like a checked checkbox or text in an input field), that state will remain with the component instance, which is now displaying the wrong data. Using a stable ID (key={product.id}) ensures React correctly identifies which element is which, preserving state and performing minimal updates.
The only time an index key is acceptable is for a list that is guaranteed to be static: it will never be reordered, filtered, or have items added or removed from the middle. This is rare in real applications.
Handle loading, empty, and error states
A production-ready component doesn't just render the "happy path." It accounts for the states before the data arrives or when the data is not what's expected. This combines conditional rendering with list management.
The order of checks is important. Handle loading and error states first. Then handle the empty state. Only then, attempt to map over the data.
function UserList() {
const { data, isLoading, error } = useUsers(); // A hypothetical data-fetching hook
if (isLoading) {
return <Spinner />;
}
if (error) {
return <ErrorMessage message={error.message} />;
}
if (!data || data.length === 0) {
return <p>No users found.</p>;
}
return (
<ul>
{data.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
This pattern is robust. It prevents runtime errors from calling .map on undefined and provides a clear user experience for every possible state of the data fetching lifecycle.
Try it
Build a component that fetches a list of items from a public API (like https://jsonplaceholder.typicode.com/todos). While fetching, show a "Loading..." message. If the fetch fails, show an error. If the list is empty, show "No items found." Otherwise, render the list. Add a button to each item that removes it from the local state. Use a stable ID for the key.
Next: Event Handling & Form Management
Lock it in — apply this lesson under interview conditions.