Course contentsShow
← React
Lesson 126 of 2,3964. Conditional Rendering in JSXFree lesson

Extract Logic to Variables Before JSX

Move complex conditional logic into variables above the return statement for clarity and easier debugging.

Extract Logic to Variables Before JSX

You'll learn: How to simplify complex conditional rendering by calculating the result before your return statement, making your JSX cleaner and easier to debug.


When your conditional logic grows beyond a simple ternary or && operator, cramming everything inline makes your JSX hard to read and harder to troubleshoot. The solution? Move that logic into well-named variables above your return statement.

Why This Matters

Think of your JSX as the presentation layer—it should show what to render, not calculate how to decide. When you bury complex conditions inside JSX, you're mixing decision-making with display, which makes both harder to understand.

The Pattern

Instead of this tangled inline mess:

return (
  <div>
    {user.age >= 18 && user.verified && !user.suspended ? <Dashboard /> : user.age >= 18 ? <VerifyPrompt /> : <AgeWarning />}
  </div>
);

Extract the logic first:

const canAccessDashboard = user.age >= 18 && user.verified && !user.suspended;
const needsVerification = user.age >= 18 && !user.verified;

return (
  <div>
    {canAccessDashboard ? <Dashboard /> : needsVerification ? <VerifyPrompt /> : <AgeWarning />}
  </div>
);

Even better, you could extract the component choice itself:

const canAccessDashboard = user.age >= 18 && user.verified && !user.suspended;
const needsVerification = user.age >= 18 && !user.verified;

const content = canAccessDashboard ? <Dashboard /> : needsVerification ? <VerifyPrompt /> : <AgeWarning />;

return <div>{content}</div>;

The Benefits

You get readable variable names that explain intent, easier debugging (check variable values instead of dissecting nested operators), and testable logic you can verify independently.

Key Takeaway: When conditional logic gets complex, calculate it in named variables before your JSX—your future self will thank you.