React Fundamentals: Conditional Rendering - Complete Guide
What is Conditional Rendering?
Conditional rendering in React is a technique where you render different UI components or elements based on certain conditions. It works exactly like conditional statements in JavaScript, but applied to JSX.
Why is it Important?
- Dynamic UIs: Creates responsive interfaces that change based on user actions or data
- Clean Code: Avoids rendering unnecessary components
- Better UX: Shows/hides elements based on application state
- Performance: Can prevent unnecessary renders
Common Patterns:
- if/else statements - Traditional JavaScript conditionals
- Ternary operators -
condition ? true : false - Logical AND (&&) operator -
condition && component - Switch statements - For multiple conditions
- Element variables - Store elements in variables
- Immediately Invoked Function Expressions (IIFE) - Execute logic in JSX
Examples
Example 1: if/else Statement
function UserGreeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
} else {
return <h1>Please sign up.</h1>;
}
}
Example 2: Ternary Operator
function Notification({ message, type }) {
return (
<div className={type === 'error' ? 'alert-error' : 'alert-success'}>
{message}
</div>
);
}
Example 3: Logical AND Operator
function ShoppingCart({ items }) {
return (
<div>
<h2>Your Cart</h2>
{items.length > 0 && (
<CartItems items={items} />
)}
</div>
);
}
Example 4: Switch Statement
function StatusIndicator({ status }) {
let statusComponent;
switch(status) {
case 'loading':
statusComponent = <Spinner />;
break;
case 'success':
statusComponent = <SuccessIcon />;
break;
case 'error':
statusComponent = <ErrorIcon />;
break;
default:
statusComponent = <InfoIcon />;
}
return <div>{statusComponent}</div>;
}
Example 5: Inline with IIFE
function UserRole({ role }) {
return (
<div>
{(() => {
if (role === 'admin') return <AdminPanel />;
if (role === 'editor') return <EditorTools />;
return <UserDashboard />;
})()}
</div>
);
}
Interview Questions & Answers
Q1: What are the different ways to implement conditional rendering in React?
Answer: React offers several conditional rendering approaches:
- if/else statements - Best for simple true/false conditions
- Ternary operator - Ideal for inline conditional rendering
- Logical AND (&&) - Perfect for rendering something or nothing
- Switch statement - Useful for multiple exclusive conditions
- Element variables - Store JSX in variables for complex logic
- Immediately Invoked Function Expressions - For complex logic within JSX
- Higher-Order Components - For reusable conditional logic
- Render props pattern - Dynamic component rendering
Q2: When would you use && operator vs ternary operator?
Answer: Use && operator when you want to render something or nothing:
{isLoading && <Spinner />}
Use ternary operator when you need to choose between two different elements:
{isLoggedIn ? <Dashboard /> : <LoginForm />}
The key difference: && only handles the "true" case, while ternary handles both true and false cases.
Q3: How do you handle multiple conditions cleanly in JSX?
Answer: For multiple conditions, avoid nested ternaries which become hard to read. Instead:
Option 1: Extract to a function
const getStatusComponent = (status) => {
if (status === 'loading') return <Spinner />;
if (status === 'error') return <ErrorMessage />;
if (status === 'empty') return <EmptyState />;
return <DataDisplay />;
};
return <div>{getStatusComponent(status)}</div>;
Option 2: Use a configuration object
const statusComponents = {
loading: <Spinner />,
error: <ErrorMessage />,
empty: <EmptyState />,
default: <DataDisplay />
};
return <div>{statusComponents[status] || statusComponents.default}</div>;
Q4: What are common pitfalls with conditional rendering?
Answer:
-
Falsy values with && operator:
0or empty string renders as falsy{items.length && <List items={items} />} // Renders 0 when array is empty!Fix:
{items.length > 0 && <List items={items} />} -
Unnecessary re-renders: Conditions that change too frequently
-
Memory leaks: Not cleaning up effects in conditionally rendered components
-
State loss: When components unmount/remount due to conditions
-
Readability issues: Overly complex nested conditions
Q5: How does conditional rendering affect component lifecycle?
Answer: When a component is conditionally rendered/unrendered:
- Unmounting: Component instance is destroyed, state is lost
- Remounting: New instance created, runs all lifecycle methods
- Updating: Component stays mounted, just updates props/state
Example showing the difference:
// This unmounts/remounts:
{showForm ? <LoginForm /> : null}
// This updates in place (if LoginForm stays rendered):
<LoginForm isVisible={showForm} />
Q6: How can you prevent unnecessary re-renders with conditional rendering?
Answer:
- Memoize components: Use
React.memo()for functional components - Use useMemo/useCallback: Memoize values and functions
- Lift conditions up: Move conditions to parent to prevent child re-renders
- Key prop strategy: Use consistent keys when conditionally rendering lists
- Component composition: Split components to isolate re-renders
Q7: How do you test components with conditional rendering?
Answer: Test all conditional branches:
// Test file
describe('UserGreeting', () => {
it('shows welcome message when logged in', () => {
render(<UserGreeting isLoggedIn={true} />);
expect(screen.getByText('Welcome back!')).toBeInTheDocument();
});
it('shows sign up prompt when not logged in', () => {
render(<UserGreeting isLoggedIn={false} />);
expect(screen.getByText('Please sign up.')).toBeInTheDocument();
});
});
Q8: What's the difference between conditional rendering and conditional styling?
Answer: Conditional rendering: Controls whether an element appears in the DOM
{isVisible && <div>Content</div>}
Conditional styling: Element always in DOM, but appearance changes
<div style={{ display: isVisible ? 'block' : 'none' }}>Content</div>
Use conditional rendering when:
- Component has heavy computations
- You need to trigger lifecycle methods
- Component has subscriptions/effects
Use conditional styling when:
- You want smooth animations
- You need to preserve component state
- Element toggles frequently
Q9: How do you handle async conditional rendering?
Answer: Handle loading, error, and data states:
function DataFetcher() {
const { data, isLoading, error } = useFetch('/api/data');
if (isLoading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;
if (!data) return <EmptyState />;
return <DataDisplay data={data} />;
}
Q10: How can you implement permission-based conditional rendering?
Answer: Create reusable permission components:
const Permission = ({ user, requiredRole, children }) => {
const userRoles = user?.roles || [];
if (!user || !userRoles.includes(requiredRole)) {
return null;
}
return children;
};
// Usage
<Permission user={currentUser} requiredRole="admin">
<AdminPanel />
</Permission>
Bonus: Advanced Pattern - Custom Hook for Conditional Rendering
function useConditionalRender(conditions) {
const renderedComponents = [];
conditions.forEach(({ condition, component }) => {
if (condition) {
renderedComponents.push(component);
}
});
return renderedComponents;
}
// Usage
function Dashboard({ user }) {
const components = useConditionalRender([
{ condition: user.isAdmin, component: <AdminPanel /> },
{ condition: user.hasNotifications, component: <Notifications /> },
{ condition: user.isNew, component: <WelcomeTutorial /> }
]);
return <div>{components}</div>;
}
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
