Conditional Rendering
Displaying different UI elements or components based on application state or props.
Mental Model
"The Toggle Switch: Flipping the wall switch changes whether the chandelier is illuminated or dark."
Interactive Engine Simulation
Conditional rendering is the power to describe multiple states of the UI in the same component. React only mounts what is needed.
Executable Code Snippet
1function AuthButton({ isLoggedIn }) {
2 // If true, render the Profile button
3 if (isLoggedIn) {
4 return <button>View Profile</button>;
5 }
6
7 // Otherwise, render the Login button
8 return <button>Log In</button>;
9}- 01.Component re-renders are triggered by state or prop changes.
- 02.Reconciliation algorithm diffs the Virtual DOM to minimize actual DOM updates.
- 03.Automatic batching optimizes multiple state updates into a single render cycle.
01. Logic in the View
Since JSX is JavaScript, we don't need a special template syntax like `ng-if` or `v-if`. We use standard JS patterns. React treats `null`, `undefined`, and `false` as "empty," meaning nothing will be rendered to the screen.
Pattern Guide
- Early Return Full block change
- Ternary (?:) Switching between two nodes
- Logical (&&) Optional visibility
02. The Zero Trap
A common "gotcha" in React is that while `false` renders nothing, the number `0` **does** render. If you write `count && <UI />` and count is 0, React will render the number '0' on your screen. Always be explicit with boolean conversions: `!!count && <UI />`.
Maintainability Note
"If your ternary expressions are nesting (e.g. condition ? a : b ? c : d), stop immediately. Move that logic into a separate helper function or a sub-component to keep the JSX readable."