Conditional Rendering

Conditional rendering selects which elements or components appear based on application state or props. In React, JavaScript expressions such as ternaries, logical `&&`, and early returns are commonly used to control the rendered UI.

Conditional rendering means deciding what React should render according to current data, state, or props. The condition is evaluated during rendering, so different conditions can produce different elements or components.

A ternary expression is useful when there are two alternatives: `condition ? <A /> : <B />`. Logical `&&` is convenient when something should appear only when a condition is truthy: `isLoggedIn && <LogoutButton />`.

For more involved conditions, an early return can make the component easier to read. For example, a component can return a loading indicator before reaching the main UI, or return an error message when required data is unavailable.

Conditional rendering does not mean hiding an element with CSS. If a branch is not selected, React does not include that branch's elements in the rendered React tree for that render. When the condition changes, React renders the newly selected branch.

Key points

Interview questions

What is conditional rendering in React?

Conditional rendering means rendering different JSX depending on a value such as state or a prop. React components can use normal JavaScript conditions to choose what should appear. Common patterns include ternaries, `&&`, and early returns. The condition is evaluated during rendering.

When would you use a ternary versus `&&` for conditional rendering?

Use a ternary when there are two meaningful UI outcomes, because it explicitly provides both branches. Use `&&` when the main requirement is to render something only when a condition is truthy. For example, `isAdmin ? <AdminPanel /> : <UserPanel />` expresses two alternatives, while `hasError && <ErrorMessage />` expresses optional UI. The choice should also keep the component readable.

What is an early return useful for in a React component?

An early return handles an exclusive state before the component reaches its main rendering logic. A common example is returning a loading indicator while data is unavailable or an error message when a request fails. This avoids deeply nested conditions around the main JSX. It can make the normal rendering path easier to understand.

What happens if you write `count && <p>{count}</p>` and count is 0?

JavaScript evaluates the left side of `&&` first. Because `0` is falsy, the right side is not evaluated, but the expression's result is `0`. In JSX, that can cause the numeric zero to be rendered rather than producing no visible output. A boolean check such as `count > 0 && <p>{count}</p>` avoids this particular issue.