Skip to main content

πŸ“˜ Conditional Rendering in React β€” Complete Theory Guide


1. Introduction

πŸ”Ή What is Conditional Rendering?

Conditional rendering in React is the process of displaying different UI elements based on certain conditions. Just like JavaScript uses if, else, or switch, React allows you to control what gets rendered depending on state, props, or logic.
{isLoggedIn ? <Dashboard /> : <Login />}

πŸ”Ή Why is it Important in React?

React is all about dynamic UI. Conditional rendering enables:
  • Personalized user experiences (e.g., logged-in vs logged-out)
  • Dynamic data-driven UI
  • Feature toggling (show/hide elements)
  • Handling async states (loading, success, error)
Without conditional rendering, your UI would be static and non-interactive.

πŸ”Ή When and Why We Use It

Use conditional rendering when:
  • Showing/hiding components
  • Handling API states (loading/error/data)
  • Rendering based on user roles or permissions
  • Toggling UI elements (modals, dropdowns)
  • Avoiding unnecessary DOM elements

2. Concepts / Internal Workings

πŸ”Ή Core Concept: React Renders Based on State/Props

React re-renders components when:
  • state changes
  • props change
Conditional rendering works by:
  1. Evaluating a condition
  2. Returning different JSX
  3. React reconciles differences via the Virtual DOM

πŸ”Ή Internal Mechanism (Reconciliation)

When a condition changes:
{isVisible && <Component />}
React:
  1. Compares previous Virtual DOM with new one
  2. Determines what changed
  3. Updates only necessary parts in the real DOM
πŸ‘‰ If condition becomes false, React removes the component πŸ‘‰ If true, React mounts the component

πŸ”Ή Truthy & Falsy Behavior

React uses JavaScript truthiness:
ValueRendered?
false❌ No
null❌ No
undefined❌ No
0βœ… Yes ⚠️
""❌ No
⚠️ Important: 0 && <Comp /> will render 0, not nothing.

πŸ”Ή Relationship with Other React Features

1. useState

Controls UI dynamically:
const [isOpen, setIsOpen] = useState(false);

2. Props

Conditional rendering based on parent data:
{user.isAdmin && <AdminPanel />}

3. Lists & Keys

Used with .map():
items.length > 0 ? items.map(...) : <EmptyState />

4. Hooks & Effects

Conditional rendering often depends on async data:
useEffect(() => {
  fetchData();
}, []);

3. Syntax & Examples

πŸ”Ή 1. if / else (Outside JSX)

Best for complex logic.
function App() {
  const isLoggedIn = true;

  if (isLoggedIn) {
    return <Dashboard />;
  } else {
    return <Login />;
  }
}

πŸ”Ή 2. Ternary Operator (Most Common)

Inline condition:
{isLoggedIn ? <Dashboard /> : <Login />}

Variation:

{isLoading ? <Loader /> : <Content />}

πŸ”Ή 3. Logical AND (&&)

Render only if condition is true:
{isVisible && <Modal />}

Variation:

{items.length > 0 && <List items={items} />}

πŸ”Ή 4. Logical OR (||)

Fallback rendering:
{username || "Guest"}

πŸ”Ή 5. Switch Case Pattern

Used for multiple conditions:
function renderContent(status) {
  switch (status) {
    case "loading":
      return <Loader />;
    case "error":
      return <Error />;
    case "success":
      return <Data />;
    default:
      return null;
  }
}

πŸ”Ή 6. Conditional Rendering with Functions

function getButton(role) {
  if (role === "admin") return <AdminButton />;
  return <UserButton />;
}

return <div>{getButton(userRole)}</div>;

πŸ”Ή 7. Rendering Null (Hide Component)

{isHidden ? null : <Component />}

πŸ”Ή 8. Inline IIFE (Advanced)

{
  (() => {
    if (isLoggedIn) return <Dashboard />;
    return <Login />;
  })()
}

πŸ”Ή 9. Multiple Conditions

{isLoggedIn && isAdmin && <AdminPanel />}

πŸ”Ή 10. Conditional CSS (Indirect Rendering)

<div className={isActive ? "active" : "inactive"} />

4. Edge Cases / Common Mistakes

⚠️ 1. Rendering 0 Accidentally

{items.length && <List />}
❌ If length = 0, React renders 0 βœ… Fix:
{items.length > 0 && <List />}

⚠️ 2. Nested Ternary Hell

{a ? (b ? <X /> : <Y />) : <Z />}
❌ Hard to read and maintain βœ… Use helper functions or variables

⚠️ 3. Returning Undefined

if (condition) {
  return;
}
❌ React expects JSX or null

⚠️ 4. Misusing && with Non-Boolean Values

{count && <Badge />}
If count = 0, it renders 0

⚠️ 5. Component State Reset on Conditional Mount

{isVisible && <Form />}
πŸ‘‰ When hidden, component is unmounted πŸ‘‰ State is lost βœ… Solution:
  • Keep mounted and hide via CSS
  • Or lift state up

⚠️ 6. Keys Issue in Conditional Lists

{isVisible && items.map(item => <Item />)}
❌ Missing key leads to reconciliation bugs

⚠️ 7. Over-rendering Due to Conditions

Frequent condition changes can cause unnecessary re-renders.

5. Best Practices

βœ… 1. Prefer Ternary for Simple Conditions

{isLoggedIn ? <Dashboard /> : <Login />}

βœ… 2. Use && for Simple Visibility

{isOpen && <Modal />}

βœ… 3. Extract Complex Logic

function renderContent() {
  if (loading) return <Loader />;
  if (error) return <Error />;
  return <Data />;
}

βœ… 4. Avoid Nested Ternaries

Use:
  • Helper functions
  • Variables
  • Separate components

βœ… 5. Use Early Returns

if (loading) return <Loader />;
if (error) return <Error />;
return <Data />;

βœ… 6. Be Careful with Truthy/Falsy Values

Always explicitly check:
{count > 0 && <Badge />}

βœ… 7. Optimize Performance

  • Avoid unnecessary mounts/unmounts
  • Use React.memo for stable components
  • Use conditional rendering to avoid heavy components

βœ… 8. Keep UI Predictable

  • Avoid flickering states
  • Handle loading/error explicitly

βœ… 9. Use Consistent Patterns

Pick a pattern and stick to it across your codebase.

βœ… 10. Combine with Suspense (Advanced)

<Suspense fallback={<Loader />}>
  {isVisible && <LazyComponent />}
</Suspense>

πŸ“Œ Summary

Conditional rendering is a core React concept that allows you to:
  • Dynamically control UI
  • Improve user experience
  • Optimize performance
Mastering it involves:
  • Understanding JavaScript conditions
  • Knowing React rendering behavior
  • Writing clean, maintainable logic

If you want, next I can create FAANG-level interview questions on conditional rendering or a real-world system design breakdown (like dashboard states, auth flows, etc.).

🧠 Advanced React Interview Questions β€” Conditional Rendering (Senior Level)


1. How does conditional rendering interact with React’s reconciliation process?

βœ… Answer

Conditional rendering directly impacts React’s reconciliation (diffing) algorithm. When a condition changes:
{isVisible && <Component />}
React compares:
  • Previous Virtual DOM: <Component />
  • New Virtual DOM: null

πŸ” What happens internally:

  • If condition becomes false β†’ component is unmounted
  • If condition becomes true β†’ component is mounted again

❗ Why this matters:

  • Mount/unmount triggers lifecycle:
    • Effects cleanup
    • State reset
  • Expensive components can hurt performance

βš–οΈ Alternative:

Instead of unmounting:
<Component style={{ display: isVisible ? "block" : "none" }} />
πŸ‘‰ Keeps component mounted β†’ preserves state πŸ‘‰ Trade-off: DOM still exists (memory cost)

2. What are the trade-offs between && and ternary (? :) for conditional rendering?

βœ… Answer

&& Operator

{isOpen && <Modal />}
βœ” Clean and concise ❌ Only works for β€œrender or nothing” ❌ Can introduce bugs with falsy values (0, "")

Ternary Operator

{isOpen ? <Modal /> : null}
βœ” Explicit behavior βœ” Supports both branches ❌ Slightly more verbose

πŸ’‘ Key Insight

Use:
  • && β†’ when rendering only on true
  • ? : β†’ when you need control over both outcomes

3. Why does React render 0 in {count && <Component />}?

βœ… Answer

Because React renders any non-boolean value except null, undefined, or false.
{0 && <Component />}
JavaScript evaluates:
0 && <Component /> // returns 0
React then renders 0.

βœ… Fix

{count > 0 && <Component />}

πŸ” Why this matters

This is a JavaScript behavior, not React-specific β€” but React exposes it in UI.

4. How does conditional rendering affect component state?

βœ… Answer

Conditional rendering can destroy component state due to unmounting.
{isVisible && <Form />}
If isVisible becomes false:
  • <Form /> is unmounted
  • All internal state is lost

πŸ” Why this happens

React removes the component from the tree β†’ memory cleared.

βš–οΈ Alternatives

1. Lift State Up

const [formData, setFormData] = useState({});

2. Keep Component Mounted

<Form hidden={!isVisible} />

πŸ’‘ Insight

Conditional rendering is not just UI β€” it’s lifecycle control.

5. What are the performance implications of conditional rendering?

βœ… Answer

Conditional rendering can either:

πŸš€ Improve performance

{isHeavyVisible && <HeavyComponent />}
βœ” Avoids rendering expensive components

🐌 Hurt performance

If toggled frequently:
  • Mount/unmount cycles
  • Re-running effects
  • Recreating DOM nodes

βš–οΈ Trade-off Strategy

ScenarioApproach
Rarely shownConditional render
Frequently toggledHide with CSS

6. How would you handle multiple UI states (loading, error, success) cleanly?

βœ… Answer

Avoid nested ternaries:
{loading ? <Loader /> : error ? <Error /> : <Data />}

βœ… Better Approach

if (loading) return <Loader />;
if (error) return <Error />;
return <Data />;

πŸ’‘ Why?

  • Improves readability
  • Easier to debug
  • Scales better

πŸ” Alternative Pattern

const renderMap = {
  loading: <Loader />,
  error: <Error />,
  success: <Data />
};

return renderMap[status];

7. What problems arise from nested conditional rendering?

βœ… Answer

{a ? (b ? <X /> : <Y />) : <Z />}

❌ Issues

  • Hard to read
  • Difficult to debug
  • Easy to introduce logic bugs

βœ… Solution

Extract logic:
function renderContent() {
  if (!a) return <Z />;
  if (b) return <X />;
  return <Y />;
}

πŸ’‘ Insight

Readable code is more important than clever code.

8. How does conditional rendering interact with keys in lists?

βœ… Answer

Incorrect conditional logic can break reconciliation:
{isVisible && items.map(item => <Item />)}
Without keys:
  • React cannot track identity
  • Leads to incorrect DOM updates

βœ… Correct

{isVisible &&
  items.map(item => <Item key={item.id} />)
}

πŸ” Why?

Keys help React:
  • Match old vs new elements
  • Avoid unnecessary re-renders

9. What is the difference between returning null and not rendering a component?

βœ… Answer

return null;
βœ” Component renders nothing βœ” Lifecycle still runs

❗ Important Distinction

CaseBehavior
return nullComponent exists, no UI
Conditional renderComponent removed entirely

πŸ’‘ Why this matters

  • useEffect still runs with null
  • Useful for logic-only components

10. How would you conditionally render components without causing layout shifts?

βœ… Answer

Frequent mount/unmount can cause layout shifts (CLS issues).

βœ… Solutions

1. Reserve space

<div style={{ minHeight: 200 }}>
  {isLoading ? <Loader /> : <Content />}
</div>

2. Skeleton loaders

{isLoading ? <Skeleton /> : <Content />}

πŸ’‘ Why?

Improves UX and avoids visual jank.

11. How does conditional rendering work with Suspense and lazy loading?

βœ… Answer

<Suspense fallback={<Loader />}>
  {isVisible && <LazyComponent />}
</Suspense>

πŸ” Behavior

  • Component loads only when condition is true
  • Suspense handles loading fallback

βš–οΈ Trade-off

  • Lazy loading reduces bundle size
  • But introduces loading delay

12. When should you avoid conditional rendering entirely?

βœ… Answer

Avoid when:
  • UI structure remains constant
  • Only styles/visibility change

❌ Example

{isActive ? <Button /> : <Button />}

βœ… Better

<Button className={isActive ? "active" : ""} />

πŸ’‘ Insight

Avoid unnecessary DOM churn.

13. How can conditional rendering lead to unnecessary re-renders?

βœ… Answer

{isVisible && <ExpensiveComponent />}
Each time isVisible toggles:
  • Component recreated
  • Effects rerun

βœ… Optimization

const Memoized = React.memo(ExpensiveComponent);

πŸ’‘ Insight

Conditional rendering affects component identity.

14. What are the risks of conditional hooks usage?

βœ… Answer

❌ Invalid:
if (isVisible) {
  useEffect(() => {});
}

πŸ”₯ Why?

Hooks must run in the same order every render.

βœ… Fix

useEffect(() => {
  if (isVisible) {
    // logic
  }
}, [isVisible]);

15. How would you design a feature toggle system using conditional rendering?

βœ… Answer

{features.newDashboard ? <NewDashboard /> : <OldDashboard />}

πŸ” Real-world considerations:

  • Remote config
  • A/B testing
  • Gradual rollout

βš–οΈ Alternative

Feature wrapper:
<Feature flag="newDashboard">
  <NewDashboard />
</Feature>

16. How does conditional rendering impact accessibility?

βœ… Answer

Removing elements:
{isOpen && <Modal />}
  • Removes from DOM β†’ screen readers can’t access

βœ… Alternative

<Modal aria-hidden={!isOpen} />

πŸ’‘ Insight

Sometimes hiding is better than removing.

17. How would you debug issues caused by conditional rendering?

βœ… Answer

Steps:

  1. Check condition values
  2. Log render cycles
console.log("render", isVisible);
  1. Use React DevTools:
    • Inspect mount/unmount
  2. Check keys and state resets

πŸ’‘ Insight

Most bugs come from:
  • Unexpected falsy values
  • State loss
  • Incorrect conditions

18. How do you decide between inline conditions vs extracted logic?

βœ… Answer

Inline

{isOpen && <Modal />}
βœ” Simple cases

Extracted

function renderModal() {
  if (!isOpen) return null;
  return <Modal />;
}
βœ” Complex logic βœ” Better readability βœ” Easier testing

πŸ’‘ Rule of Thumb

  • Simple β†’ inline
  • Complex β†’ extract

πŸ“Œ Final Takeaway

Conditional rendering is not just about showing/hiding UI β€” it affects:
  • Component lifecycle
  • Performance
  • State management
  • Accessibility
  • Code maintainability
Senior engineers treat it as a design decision, not just syntax.

🧠 Advanced MCQs β€” Conditional Rendering in React (Senior Level)


1. What will React render?

{0 && <h1>Hello</h1>}

Options:

A. Nothing B. <h1>Hello</h1> C. 0 D. Error

βœ… Correct Answer: C

πŸ’‘ Explanation:

  • JavaScript evaluates 0 && <h1>Hello</h1> β†’ 0
  • React renders any non-null/undefined/false value, including 0

❌ Why others are wrong:

  • A: React does not ignore 0
  • B: Condition is falsy, so JSX is not evaluated
  • D: No syntax/runtime error

2. What happens when isVisible toggles frequently?

{isVisible && <ExpensiveComponent />}

Options:

A. Component updates but is not recreated B. Component is unmounted and remounted each time C. Only props update D. React caches the component automatically

βœ… Correct Answer: B

πŸ’‘ Explanation:

  • When condition flips:
    • true β†’ false β†’ unmount
    • false β†’ true β†’ remount
  • Causes:
    • State reset
    • Effects rerun

❌ Why others are wrong:

  • A/C: No update β€” it’s full mount/unmount
  • D: React does NOT cache components automatically

3. What is rendered?

{"" && <Component />}

Options:

A. <Component /> B. "" (empty string rendered) C. Nothing D. Error

βœ… Correct Answer: C

πŸ’‘ Explanation:

  • "" is falsy β†’ expression returns ""
  • React treats empty string as non-rendered

❌ Why others are wrong:

  • A: Condition is falsy
  • B: React does not render empty string visibly
  • D: No error

4. Which approach preserves component state?

Options:

A.
{isOpen && <Modal />}
B.
{isOpen ? <Modal /> : null}
C.
<Modal hidden={!isOpen} />
D.
if (isOpen) return <Modal />

βœ… Correct Answer: C

πŸ’‘ Explanation:

  • Component is always mounted
  • Only visibility changes β†’ state preserved

❌ Why others are wrong:

  • A/B/D: Component is removed β†’ state lost

5. What is the output?

{false || <div>Hi</div>}

Options:

A. false B. <div>Hi</div> C. Nothing D. Error

βœ… Correct Answer: B

πŸ’‘ Explanation:

  • false || <div> β†’ returns <div>
  • React renders it

❌ Why others are wrong:

  • A: || returns second operand
  • C: JSX exists
  • D: Valid syntax

6. Which scenario can cause layout shift issues?

Options:

A.
<div>{isLoading && <Loader />}</div>
B.
<div style={{ minHeight: 200 }}>
  {isLoading ? <Loader /> : <Content />}
</div>
C.
<Loader />
D.
{true && <Content />}

βœ… Correct Answer: A

πŸ’‘ Explanation:

  • Loader appears/disappears β†’ DOM height changes β†’ layout shift

❌ Why others are wrong:

  • B: Space reserved β†’ no shift
  • C/D: No conditional toggle

7. What is the issue here?

{items.length && <List items={items} />}

Options:

A. Performance issue B. Incorrect rendering when empty C. Syntax error D. Infinite loop

βœ… Correct Answer: B

πŸ’‘ Explanation:

  • When items.length = 0, React renders 0

❌ Why others are wrong:

  • A: Not necessarily
  • C/D: No syntax or loop issue

8. Which is the cleanest approach for multiple UI states?

Options:

A.
{loading ? <A /> : error ? <B /> : <C />}
B.
if (loading) return <A />;
if (error) return <B />;
return <C />;
C.
loading && <A />
error && <B />
D.
switch(true) {}

βœ… Correct Answer: B

πŸ’‘ Explanation:

  • Clear, readable, scalable
  • Avoids nested ternary complexity

❌ Why others are wrong:

  • A: Hard to maintain
  • C: Multiple renders possible
  • D: Non-idiomatic

9. What happens if hooks are used conditionally?

if (isVisible) {
  useEffect(() => {});
}

Options:

A. Works fine B. Runs only when visible C. Breaks hook rules D. Skips execution

βœ… Correct Answer: C

πŸ’‘ Explanation:

  • Hooks must run in same order every render
  • Conditional usage breaks React internals

❌ Why others are wrong:

  • A/B/D: Incorrect β€” this causes runtime issues

10. What is rendered?

{null && <Component />}

Options:

A. <Component /> B. null C. Nothing D. Error

βœ… Correct Answer: C

πŸ’‘ Explanation:

  • null is falsy β†’ React renders nothing

❌ Why others are wrong:

  • A: Condition fails
  • B: React doesn’t render null visibly
  • D: No error

11. Which approach avoids unnecessary remounting?

Options:

A.
{isOpen && <Heavy />}
B.
{isOpen ? <Heavy /> : <></>}
C.
<Heavy style={{ display: isOpen ? "block" : "none" }} />
D.
return isOpen && <Heavy />

βœ… Correct Answer: C

πŸ’‘ Explanation:

  • Component always mounted β†’ no remount

❌ Why others are wrong:

  • A/B/D: Component removed from tree

12. What happens in this scenario?

{isAdmin && isLoggedIn && <AdminPanel />}

Options:

A. Renders if either condition is true B. Renders only if both are true C. Always renders D. Throws error

βœ… Correct Answer: B

πŸ’‘ Explanation:

  • Logical AND chain β†’ all must be truthy

❌ Why others are wrong:

  • A: That’s OR behavior
  • C/D: Incorrect

13. Which pattern is best for feature flags?

Options:

A.
if (flag) return <New />
B.
{flag ? <New /> : <Old />}
C.
flag && <New />
D.
<Feature flag="new" />

βœ… Correct Answer: B

πŸ’‘ Explanation:

  • Explicit fallback ensures predictable UI

❌ Why others are wrong:

  • A: Removes fallback UI
  • C: No fallback
  • D: Incomplete abstraction

14. What happens when a component returns null?

Options:

A. Component is unmounted B. Component is skipped entirely C. Component exists but renders nothing D. React throws warning

βœ… Correct Answer: C

πŸ’‘ Explanation:

  • Component lifecycle still runs
  • Only UI output is empty

❌ Why others are wrong:

  • A/B: Component still exists
  • D: No warning

15. What is the problem with this code?

{a ? <X /> : b ? <Y /> : c ? <Z /> : null}

Options:

A. Syntax error B. Too many re-renders C. Poor readability and maintainability D. React cannot evaluate it

βœ… Correct Answer: C

πŸ’‘ Explanation:

  • Nested ternaries reduce clarity
  • Hard to debug and scale

❌ Why others are wrong:

  • A/D: Valid syntax
  • B: Not inherently causing re-renders

16. Which case may cause accessibility issues?

Options:

A.
{isOpen && <Modal />}
B.
<Modal aria-hidden={!isOpen} />
C.
<Modal />
D.
null

βœ… Correct Answer: A

πŸ’‘ Explanation:

  • Removing element from DOM β†’ screen readers lose access

❌ Why others are wrong:

  • B: Maintains accessibility control
  • C/D: Not conditional

17. What is the output?

{undefined && <Comp />}

Options:

A. <Comp /> B. undefined C. Nothing D. Error

βœ… Correct Answer: C

πŸ’‘ Explanation:

  • undefined is ignored by React rendering

❌ Why others are wrong:

  • A: Condition falsy
  • B: Not rendered
  • D: No error

18. Which scenario is best for conditional rendering?

Options:

A. Toggling visibility frequently B. Rendering heavy component rarely C. Styling changes D. Static UI

βœ… Correct Answer: B

πŸ’‘ Explanation:

  • Avoid rendering heavy components unless needed

❌ Why others are wrong:

  • A: Better to hide
  • C: Use CSS
  • D: No condition needed

πŸ“Œ Final Insight

These questions test true senior-level understanding:
  • React reconciliation behavior
  • Lifecycle implications
  • JavaScript quirks affecting UI
  • Performance trade-offs
  • Accessibility & maintainability

πŸ’» Advanced Coding Problems β€” Conditional Rendering in React (Senior Level)


🧩 Problem 1: Role-Based Dashboard Rendering

πŸ“Œ Problem Statement

Build a dashboard that renders different UI based on user roles (admin, editor, viewer).

Constraints

  • Role comes from API (async)
  • Must handle loading + error states
  • Avoid nested conditionals

Expected Behavior

  • admin β†’ Full dashboard
  • editor β†’ Limited controls
  • viewer β†’ Read-only

Edge Cases

  • Unknown role
  • API failure
  • Role changes dynamically

βœ… Solution Approach

function Dashboard({ role, loading, error }) {
  if (loading) return <Loader />;
  if (error) return <Error />;

  const roleMap = {
    admin: <AdminDashboard />,
    editor: <EditorDashboard />,
    viewer: <ViewerDashboard />,
  };

  return roleMap[role] || <NotAuthorized />;
}

πŸ’‘ Why this works

  • Avoids nested if-else
  • Scalable for new roles

🧩 Problem 2: Feature Flag System

πŸ“Œ Problem Statement

Render features based on remote config flags.

Constraints

  • Flags can change at runtime
  • Must support fallback UI

Expected Behavior

  • Show new feature if enabled
  • Else show old UI

βœ… Solution

function Feature({ flag, children, fallback }) {
  return flag ? children : fallback;
}
Usage:
<Feature flag={flags.newUI} fallback={<OldUI />}>
  <NewUI />
</Feature>

πŸ’‘ Insight

Encapsulates conditional logic β†’ reusable + testable

🧩 Problem 3: Async Data Rendering (Loading/Error/Data)

πŸ“Œ Problem Statement

Display API data with proper states.

Constraints

  • No nested ternaries
  • Clean separation

βœ… Solution

function DataComponent({ status, data }) {
  switch (status) {
    case "loading":
      return <Loader />;
    case "error":
      return <Error />;
    case "success":
      return <Data data={data} />;
    default:
      return null;
  }
}

πŸ’‘ Why

Switch pattern improves readability over nested ternaries

🧩 Problem 4: Preserve Form State on Toggle

πŸ“Œ Problem Statement

A form should not lose input when hidden.

Constraints

  • Toggle visibility frequently

❌ Wrong

{isVisible && <Form />}

βœ… Correct

<Form style={{ display: isVisible ? "block" : "none" }} />

πŸ’‘ Insight

Avoid unmounting β†’ preserves state

🧩 Problem 5: Conditional List Rendering with Empty State

πŸ“Œ Problem Statement

Render list or empty state.

❌ Buggy

{items.length && <List />}

βœ… Solution

{items.length > 0 ? <List items={items} /> : <Empty />}

Edge Case

  • items = [] should not render 0

🧩 Problem 6: Permission-Based Button Rendering

πŸ“Œ Problem Statement

Show buttons based on permissions array.

βœ… Solution

function Actions({ permissions }) {
  return (
    <>
      {permissions.includes("edit") && <Edit />}
      {permissions.includes("delete") && <Delete />}
    </>
  );
}

πŸ’‘ Insight

Declarative + composable

🧩 Problem 7: Dynamic Layout Rendering

πŸ“Œ Problem Statement

Render different layouts (grid, list)

βœ… Solution

const layoutMap = {
  grid: <GridView />,
  list: <ListView />,
};

return layoutMap[layout];

🧩 Problem 8: Prevent Layout Shift (Skeleton Loader)

πŸ“Œ Problem Statement

Avoid UI jump during loading.

βœ… Solution

<div style={{ minHeight: 200 }}>
  {loading ? <Skeleton /> : <Content />}
</div>

🧩 Problem 9: Multi-Step Form Rendering

πŸ“Œ Problem Statement

Render steps based on current index.

βœ… Solution

const steps = [<Step1 />, <Step2 />, <Step3 />];

return steps[currentStep];

Edge Case

  • Invalid index

🧩 Problem 10: Conditional Modal with State Persistence

πŸ“Œ Problem Statement

Modal should not reset when reopened.

βœ… Solution

<Modal isOpen={isOpen} />
Inside Modal:
return (
  <div style={{ display: isOpen ? "block" : "none" }}>
    {/* content */}
  </div>
);

🧩 Problem 11: A/B Testing UI

πŸ“Œ Problem Statement

Render UI variant based on experiment.

βœ… Solution

const variantMap = {
  A: <VariantA />,
  B: <VariantB />,
};

return variantMap[variant];

🧩 Problem 12: Nested Permission + State Logic

πŸ“Œ Problem Statement

Render admin panel only if:
  • logged in
  • is admin
  • feature enabled

βœ… Solution

if (!isLoggedIn) return <Login />;
if (!isAdmin) return <Forbidden />;
if (!featureFlag) return null;

return <AdminPanel />;

🧩 Problem 13: Conditional Rendering with Suspense

πŸ“Œ Problem Statement

Lazy load component only when visible.

βœ… Solution

<Suspense fallback={<Loader />}>
  {isVisible && <LazyComponent />}
</Suspense>

🧩 Problem 14: Conditional Wrapper Component

πŸ“Œ Problem Statement

Wrap content only if condition is true.

βœ… Solution

function ConditionalWrapper({ condition, wrapper, children }) {
  return condition ? wrapper(children) : children;
}
Usage:
<ConditionalWrapper
  condition={isLink}
  wrapper={(child) => <a href="/">{child}</a>}
>
  <Button />
</ConditionalWrapper>

🧩 Problem 15: Error Boundary Fallback Rendering

πŸ“Œ Problem Statement

Render fallback UI on error.

βœ… Solution

{hasError ? <Fallback /> : <Component />}

🧩 Problem 16: Conditional Animation Mount

πŸ“Œ Problem Statement

Animate component only when entering.

βœ… Solution

{isVisible && <AnimatedComponent />}

Edge Case

  • Animation reset on remount

🧩 Problem 17: Render Different Components Based on Screen Size

πŸ“Œ Problem Statement

Mobile vs Desktop rendering.

βœ… Solution

return isMobile ? <MobileView /> : <DesktopView />;

🧩 Problem 18: Debounced Conditional Rendering

πŸ“Œ Problem Statement

Render search results only after debounce.

βœ… Solution

{debouncedQuery && <Results />}

🧩 Problem 19: Conditional Rendering with Memoization

πŸ“Œ Problem Statement

Avoid re-render of heavy component.

βœ… Solution

const MemoComp = React.memo(Heavy);

return isVisible && <MemoComp />;

🧩 Problem 20: Progressive Disclosure UI

πŸ“Œ Problem Statement

Show more content when user clicks β€œShow More”.

βœ… Solution

{showMore && <ExtraContent />}
<button onClick={() => setShowMore(true)}>Show More</button>

πŸ“Œ Final Takeaways

These problems test:
  • Component lifecycle awareness
  • State persistence vs unmounting
  • Performance optimization
  • Readable conditional patterns
  • Real-world UI complexity

πŸ› Advanced Debugging Challenges β€” Conditional Rendering in React (Senior Level)


🧩 1. Rendering 0 Instead of Nothing

❌ Buggy Code

{items.length && <List items={items} />}

πŸ” What’s Wrong?

When items.length === 0, React renders 0.

πŸ’‘ Why It Happens

  • 0 && <List /> evaluates to 0
  • React renders numbers

βœ… Fixed Code

{items.length > 0 && <List items={items} />}

🧠 Best Practice

Always explicitly check numeric conditions.

🧩 2. State Reset on Toggle

❌ Buggy Code

{isOpen && <Form />}

πŸ” What’s Wrong?

Form input resets when toggled.

πŸ’‘ Why It Happens

Component is unmounted β†’ state lost.

βœ… Fixed Code

<Form style={{ display: isOpen ? "block" : "none" }} />

🧠 Best Practice

Avoid unmounting when state persistence is needed.

🧩 3. Nested Ternary Logic Bug

❌ Buggy Code

{isAdmin ? isActive ? <A /> : <B /> : <C />}

πŸ” What’s Wrong?

Hard to reason; easy to misinterpret logic.

πŸ’‘ Why It Happens

Nested ternaries reduce readability β†’ bugs slip in.

βœ… Fixed Code

if (!isAdmin) return <C />;
return isActive ? <A /> : <B />;

🧠 Best Practice

Avoid nested ternaries beyond one level.

🧩 4. Component Re-Mount Performance Issue

❌ Buggy Code

{showChart && <HeavyChart data={data} />}

πŸ” What’s Wrong?

Chart re-initializes on every toggle.

πŸ’‘ Why It Happens

Unmount β†’ remount β†’ expensive setup runs again.

βœ… Fixed Code

<HeavyChart hidden={!showChart} data={data} />

🧠 Best Practice

Keep expensive components mounted if frequently toggled.

🧩 5. Conditional Hook Execution

❌ Buggy Code

if (isVisible) {
  useEffect(() => {
    fetchData();
  }, []);
}

πŸ” What’s Wrong?

Breaks React hook rules.

πŸ’‘ Why It Happens

Hooks must run in consistent order every render.

βœ… Fixed Code

useEffect(() => {
  if (isVisible) {
    fetchData();
  }
}, [isVisible]);

🧠 Best Practice

Never call hooks conditionally.

🧩 6. Missing Fallback UI

❌ Buggy Code

{isEnabled && <Feature />}

πŸ” What’s Wrong?

Nothing renders when disabled β†’ confusing UX.

πŸ’‘ Why It Happens

No fallback branch defined.

βœ… Fixed Code

{isEnabled ? <Feature /> : <Fallback />}

🧠 Best Practice

Always define fallback for critical UI.

🧩 7. Incorrect OR Usage

❌ Buggy Code

{username || <Guest />}

πŸ” What’s Wrong?

If username = "0" or "false" β†’ unexpected render.

πŸ’‘ Why It Happens

JS truthy/falsy confusion.

βœ… Fixed Code

{username ? username : <Guest />}

🧠 Best Practice

Avoid relying on implicit truthiness for UI.

🧩 8. Flickering UI Due to Rapid Toggle

❌ Buggy Code

{loading && <Spinner />}
{!loading && <Content />}

πŸ” What’s Wrong?

Flickering during quick state transitions.

πŸ’‘ Why It Happens

Two separate conditions β†’ race conditions in render.

βœ… Fixed Code

{loading ? <Spinner /> : <Content />}

🧠 Best Practice

Use a single conditional branch.

🧩 9. Key Misuse in Conditional List

❌ Buggy Code

{isVisible &&
  items.map((item, i) => <Item key={i} />)
}

πŸ” What’s Wrong?

Incorrect DOM updates when list changes.

πŸ’‘ Why It Happens

Index keys break reconciliation.

βœ… Fixed Code

items.map(item => <Item key={item.id} />)

🧠 Best Practice

Never use index as key in dynamic lists.

🧩 10. Returning Undefined

❌ Buggy Code

if (!data) return;

πŸ” What’s Wrong?

React expects JSX or null.

πŸ’‘ Why It Happens

Returning undefined is not valid render output.

βœ… Fixed Code

if (!data) return null;

🧠 Best Practice

Always return null for empty render.

🧩 11. Duplicate Rendering Conditions

❌ Buggy Code

{isOpen && <Modal />}
{isOpen && <Backdrop />}

πŸ” What’s Wrong?

Logic duplicated β†’ harder to maintain.

πŸ’‘ Why It Happens

Conditions scattered.

βœ… Fixed Code

{isOpen && (
  <>
    <Backdrop />
    <Modal />
  </>
)}

🧠 Best Practice

Group related conditional UI.

🧩 12. Layout Shift Issue

❌ Buggy Code

{isLoading ? <Loader /> : <Content />}

πŸ” What’s Wrong?

Content jumps when loader disappears.

πŸ’‘ Why It Happens

Different component sizes.

βœ… Fixed Code

<div style={{ minHeight: 200 }}>
  {isLoading ? <Loader /> : <Content />}
</div>

🧠 Best Practice

Reserve layout space.

🧩 13. Conditional Rendering Inside Map

❌ Buggy Code

items.map(item => item.visible && <Item />)

πŸ” What’s Wrong?

Returns false values in array.

πŸ’‘ Why It Happens

Falsy values still exist in array β†’ subtle issues.

βœ… Fixed Code

items
  .filter(item => item.visible)
  .map(item => <Item key={item.id} />);

🧠 Best Practice

Filter before mapping.

🧩 14. Wrong Conditional Wrapper

❌ Buggy Code

{isLink && <a><Button /></a>}
{!isLink && <Button />}

πŸ” What’s Wrong?

Duplicate JSX.

πŸ’‘ Why It Happens

Wrapper logic not abstracted.

βœ… Fixed Code

const Wrapper = isLink ? "a" : React.Fragment;

<Wrapper>
  <Button />
</Wrapper>

🧠 Best Practice

Use conditional wrappers.

🧩 15. Expensive Computation on Every Render

❌ Buggy Code

{isVisible && <Chart data={computeData()} />}

πŸ” What’s Wrong?

computeData() runs every render.

πŸ’‘ Why It Happens

Function executes before condition check.

βœ… Fixed Code

{isVisible && <Chart data={memoizedData} />}

🧠 Best Practice

Memoize expensive computations.

🧩 16. Incorrect Default Case Handling

❌ Buggy Code

const map = {
  success: <Success />,
  error: <Error />
};

return map[status];

πŸ” What’s Wrong?

Returns undefined for unknown status.

πŸ’‘ Why It Happens

No fallback defined.

βœ… Fixed Code

return map[status] || <Fallback />;

🧠 Best Practice

Always handle unknown states.

🧩 17. Multiple Conditions Causing Hidden Bugs

❌ Buggy Code

{isLoggedIn && isAdmin && <Panel />}

πŸ” What’s Wrong?

No feedback if condition fails.

πŸ’‘ Why It Happens

Silent failure β†’ bad UX.

βœ… Fixed Code

if (!isLoggedIn) return <Login />;
if (!isAdmin) return <Forbidden />;
return <Panel />;

🧠 Best Practice

Make failure states explicit.

🧩 18. Conditional Rendering Breaking Animation

❌ Buggy Code

{isVisible && <FadeIn />}

πŸ” What’s Wrong?

Animation restarts every mount.

πŸ’‘ Why It Happens

Component recreated each time.

βœ… Fixed Code

<FadeIn visible={isVisible} />

🧠 Best Practice

Control animation via props, not mount/unmount.

πŸ“Œ Final Takeaway

These bugs highlight real production issues:
  • ⚠️ JavaScript quirks leaking into UI
  • ⚠️ React lifecycle misunderstandings
  • ⚠️ Performance pitfalls
  • ⚠️ UX inconsistencies

πŸ—οΈ Advanced Machine Coding Problems β€” Conditional Rendering in React (Senior Architect Level)

These are production-grade problems designed to test architecture, state design, rendering strategy, and performance thinking β€” not just syntax.

🧩 1. Role-Based Multi-Tenant Dashboard

πŸ“Œ Requirements

  • Different UI per role: admin, manager, user
  • Widgets vary per tenant + role
  • Data loads asynchronously

🎯 UI Behavior

  • Skeleton β†’ Dashboard
  • Role switch updates UI instantly
  • Unauthorized widgets hidden

πŸ”„ State/Data Flow

  • Global: user, tenant, permissions
  • Local: widget loading states

⚠️ Edge Cases

  • Unknown role
  • Partial permissions
  • Tenant switch mid-session

⚑ Performance

  • Avoid re-rendering all widgets on role change

πŸ—οΈ Suggested Architecture

  • Config-driven rendering:
const widgetMap = {
  admin: [A, B, C],
  user: [A],
};

πŸͺœ Solution Approach

  1. Fetch user + permissions
  2. Build widget config
  3. Render via map
  4. Memoize widgets

🧩 2. Feature Flag + Remote Config System

πŸ“Œ Requirements

  • Toggle features dynamically
  • Support A/B testing

🎯 UI Behavior

  • New/old UI swap without reload

πŸ”„ Data Flow

  • Remote config service
  • Cached flags

⚠️ Edge Cases

  • Flag loading delay
  • Missing flags

⚑ Performance

  • Avoid flicker on flag load

πŸ—οΈ Architecture

  • <Feature flag="x" fallback={...}>

πŸͺœ Approach

  1. Fetch flags
  2. Cache globally
  3. Conditional wrapper
  4. Suspense for loading

🧩 3. Async Data State Manager (Loading/Error/Empty/Success)

πŸ“Œ Requirements

Handle all API states consistently across app

🎯 UI Behavior

  • Loader β†’ Data OR Empty OR Error

⚠️ Edge Cases

  • Partial data
  • Retry logic

⚑ Performance

  • Avoid unnecessary re-renders

πŸ—οΈ Architecture

  • Reusable <DataState /> component

πŸͺœ Approach

  1. Normalize API state
  2. Use switch/map rendering
  3. Inject children for success

🧩 4. Progressive Disclosure Form (Multi-Step + Conditional Fields)

πŸ“Œ Requirements

  • Steps change based on user input
  • Some fields appear conditionally

🎯 UI Behavior

  • Dynamic steps
  • Validation per step

⚠️ Edge Cases

  • Back navigation
  • Skipped steps

⚑ Performance

  • Preserve form state

πŸ—οΈ Architecture

  • Step config array

πŸͺœ Approach

  1. Central form state
  2. Conditional step rendering
  3. Persist hidden fields

🧩 5. Real-Time Notification Panel

πŸ“Œ Requirements

  • Show notifications if available
  • Group by type

🎯 UI Behavior

  • Empty β†’ β€œNo notifications”
  • Live updates

⚠️ Edge Cases

  • Duplicate notifications
  • Rapid updates

⚑ Performance

  • Avoid re-rendering entire list

πŸ—οΈ Architecture

  • Virtualized list + conditional sections

πŸͺœ Approach

  1. Normalize data
  2. Conditional grouping
  3. Memoize items

🧩 6. Conditional Layout System (Responsive + Feature-Based)

πŸ“Œ Requirements

  • Layout changes based on:
    • screen size
    • feature flags

🎯 UI Behavior

  • Mobile vs Desktop layouts

⚠️ Edge Cases

  • Resize during render

⚑ Performance

  • Avoid full layout re-render

πŸ—οΈ Architecture

const layoutMap = { mobile: M, desktop: D };

πŸͺœ Approach

  1. Detect device
  2. Combine with flags
  3. Render layout map

🧩 7. Lazy Loaded Modal System

πŸ“Œ Requirements

  • Load modal only when opened

🎯 UI Behavior

  • Instant open after first load

⚠️ Edge Cases

  • Reopen quickly

⚑ Performance

  • Avoid repeated imports

πŸ—οΈ Architecture

  • React.lazy + Suspense

πŸͺœ Approach

  1. Lazy import modal
  2. Conditional render
  3. Cache component

🧩 8. Permission-Based Routing Guard

πŸ“Œ Requirements

  • Protect routes based on roles

🎯 UI Behavior

  • Redirect or fallback UI

⚠️ Edge Cases

  • Role fetch delay

⚑ Performance

  • Avoid flashing unauthorized UI

πŸ—οΈ Architecture

  • <ProtectedRoute />

πŸͺœ Approach

  1. Fetch auth state
  2. Conditional render route
  3. Show loader until resolved

🧩 9. Skeleton Loader System

πŸ“Œ Requirements

  • Replace loaders with skeleton UI

🎯 UI Behavior

  • Layout remains stable

⚠️ Edge Cases

  • Partial loading

⚑ Performance

  • Avoid layout shift

πŸ—οΈ Architecture

  • Skeleton wrapper component

🧩 10. Dynamic Table with Conditional Columns

πŸ“Œ Requirements

  • Columns shown based on user role

🎯 UI Behavior

  • Admin sees extra columns

⚠️ Edge Cases

  • Column mismatch

⚑ Performance

  • Avoid recalculating columns each render

πŸ—οΈ Architecture

  • Column config map

🧩 11. Error Boundary UI Switcher

πŸ“Œ Requirements

  • Show fallback UI on failure

🎯 UI Behavior

  • Retry button

⚠️ Edge Cases

  • Partial failures

πŸ—οΈ Architecture

  • ErrorBoundary + conditional fallback

🧩 12. Chat App Message Rendering

πŸ“Œ Requirements

  • Render messages differently:
    • text
    • image
    • system

🎯 UI Behavior

  • Different UI per type

⚠️ Edge Cases

  • Unknown message type

πŸ—οΈ Architecture

const messageMap = { text: T, image: I };

🧩 13. Infinite Scroll Feed with Conditional Sections

πŸ“Œ Requirements

  • Feed includes ads, posts, suggestions

🎯 UI Behavior

  • Mixed content rendering

⚠️ Edge Cases

  • Empty feed

⚑ Performance

  • Virtualization

🧩 14. Multi-State Button (Loading/Success/Error)

πŸ“Œ Requirements

  • Button changes state dynamically

🎯 UI Behavior

  • Spinner β†’ Success β†’ Reset

⚠️ Edge Cases

  • Rapid clicks

πŸ—οΈ Architecture

  • State-driven rendering

πŸ“Œ Requirements

  • Render as <a> or <button>

πŸ—οΈ Architecture

  • Wrapper pattern

🧩 16. A/B Testing Landing Page

πŸ“Œ Requirements

  • Different layouts per experiment

⚠️ Edge Cases

  • Switching variants mid-session

🧩 17. Accessibility-Aware Modal Rendering

πŸ“Œ Requirements

  • Modal hidden but accessible

⚠️ Edge Cases

  • Screen reader behavior

🧩 18. Search Results with Debounced Rendering

πŸ“Œ Requirements

  • Show results only after debounce

⚠️ Edge Cases

  • Empty query

🧩 19. File Upload UI with State Transitions

πŸ“Œ Requirements

  • Upload β†’ Progress β†’ Success/Error

πŸ—οΈ Architecture

  • State machine rendering

🧩 20. Conditional Animation System

πŸ“Œ Requirements

  • Animate entry/exit without remount issues

⚠️ Edge Cases

  • Animation reset

πŸ“Œ Final Takeaways

These problems test:
  • 🧠 Architectural thinking
  • βš™οΈ State modeling
  • πŸ” Render lifecycle understanding
  • πŸš€ Performance optimization
  • 🧩 Composable UI patterns

🧠 FAANG-Level Interview Questions β€” Conditional Rendering (React)


1. How does conditional rendering impact component lifecycle and why does it matter?

πŸ” Follow-up

  • How would you preserve state when toggling UI?
  • When is unmounting actually beneficial?

βœ… Strong Answer

Conditional rendering controls whether a component is mounted or unmounted.
{isOpen && <Modal />}
  • true β†’ false β†’ unmount β†’ state lost, effects cleaned
  • false β†’ true β†’ mount β†’ fresh instance
πŸ‘‰ This matters because:
  • Expensive components may reinitialize
  • State resets unexpectedly
  • Effects rerun

βš–οΈ Trade-off

  • Unmount β†’ saves memory
  • Keep mounted β†’ preserves state

❌ Weak Answer

β€œReact just hides the component.” πŸ‘‰ Fails because React removes it from the tree, not just hides it.

2. When would you avoid conditional rendering entirely?

πŸ” Follow-up

  • What would you use instead?
  • Give a real-world example

βœ… Strong Answer

Avoid when:
  • Component is frequently toggled
  • State must persist
Use CSS visibility instead:
<Component style={{ display: isVisible ? "block" : "none" }} />

βš–οΈ Trade-off

  • Conditional rendering β†’ clean DOM
  • CSS hiding β†’ better performance for frequent toggles

❌ Weak Answer

β€œAlways use conditional rendering for showing/hiding.” πŸ‘‰ Ignores performance + lifecycle implications

3. Explain a real bug caused by {count && <Component />}

πŸ” Follow-up

  • How would you fix it?
  • Why does it happen?

βœ… Strong Answer

If count = 0, React renders 0.
{count && <Badge />}
Fix:
{count > 0 && <Badge />}

πŸ’‘ Why

JS returns 0, and React renders it.

❌ Weak Answer

β€œIt works fine unless count is null.” πŸ‘‰ Misses JS truthiness nuance

4. How do you design conditional rendering for multiple UI states at scale?

πŸ” Follow-up

  • How do you avoid nested ternaries?
  • How do you make it reusable?

βœ… Strong Answer

Use state mapping or early returns:
if (loading) return <Loader />;
if (error) return <Error />;
return <Data />;
Or:
const map = { loading: <L />, error: <E />, success: <D /> };
return map[status];

πŸ’‘ Why

  • Scalable
  • Readable
  • Easy to extend

❌ Weak Answer

β€œUse ternary operator.” πŸ‘‰ Doesn’t scale for complex states

5. What are the performance implications of conditional rendering?

πŸ” Follow-up

  • When does it hurt performance?
  • How would you optimize?

βœ… Strong Answer

  • Frequent mount/unmount β†’ expensive
  • Effects rerun β†’ CPU cost
  • DOM recreated β†’ layout cost
Optimization:
  • Keep mounted for frequent toggles
  • Use React.memo
  • Lazy load heavy components

❌ Weak Answer

β€œIt improves performance because less DOM.” πŸ‘‰ Oversimplified and sometimes incorrect

6. How does conditional rendering interact with React reconciliation?

πŸ” Follow-up

  • What happens internally when condition flips?
  • How do keys affect this?

βœ… Strong Answer

React compares previous vs new tree:
{isVisible && <Comp />}
  • If removed β†’ React deletes node
  • If added β†’ React creates new node
Keys help React identify elements correctly.

❌ Weak Answer

β€œReact just updates the DOM.” πŸ‘‰ Lacks understanding of Virtual DOM diffing

7. How would you prevent UI flickering during rapid state changes?

πŸ” Follow-up

  • What causes flickering?
  • How would you stabilize UI?

βœ… Strong Answer

Use single conditional branch:
{loading ? <Loader /> : <Content />}
Also:
  • Debounce state updates
  • Use skeleton loaders

❌ Weak Answer

β€œUse CSS transitions.” πŸ‘‰ Doesn’t address root cause

8. Explain trade-offs between &&, ternary, and function-based rendering

πŸ” Follow-up

  • When would you choose each?

βœ… Strong Answer

  • && β†’ simple visibility
  • ? : β†’ explicit branching
  • function β†’ complex logic
function render() {
  if (...) return ...
}

❌ Weak Answer

β€œThey are interchangeable.” πŸ‘‰ Ignores readability and intent

9. How do you handle conditional rendering with async data safely?

πŸ” Follow-up

  • What bugs can occur?
  • How do you prevent them?

βœ… Strong Answer

Handle all states:
if (loading) return <Loader />;
if (error) return <Error />;
if (!data) return <Empty />;
Avoid:
  • rendering before data exists
  • undefined errors

❌ Weak Answer

β€œJust check if data exists.” πŸ‘‰ Incomplete handling

10. What is the difference between returning null vs conditionally rendering a component?

πŸ” Follow-up

  • Does lifecycle run in both cases?

βœ… Strong Answer

  • return null β†’ component exists, no UI
  • Conditional render β†’ component removed
Lifecycle:
  • null β†’ effects still run
  • conditional β†’ no lifecycle

❌ Weak Answer

β€œThey are the same.” πŸ‘‰ Incorrect

11. How would you design a feature flag system using conditional rendering?

πŸ” Follow-up

  • How do you avoid flicker?
  • How do you scale this?

βœ… Strong Answer

<Feature flag="newUI" fallback={<Old />}>
  <New />
</Feature>
  • Centralized logic
  • Supports A/B testing

❌ Weak Answer

β€œUse if condition everywhere.” πŸ‘‰ Not scalable

12. What are common accessibility issues with conditional rendering?

πŸ” Follow-up

  • When should you hide vs remove?

βœ… Strong Answer

Removing elements:
{isOpen && <Modal />}
  • Screen readers lose access
Use:
<Modal aria-hidden={!isOpen} />

❌ Weak Answer

β€œNo impact on accessibility.” πŸ‘‰ Incorrect

13. How do you debug unexpected rendering issues?

πŸ” Follow-up

  • What tools do you use?

βœ… Strong Answer

  • Log condition values
  • Use React DevTools
  • Check mount/unmount cycles
  • Verify keys and state

❌ Weak Answer

β€œCheck console errors.” πŸ‘‰ Too shallow

14. How can conditional rendering lead to memory leaks or performance issues?

πŸ” Follow-up

  • Example?

βœ… Strong Answer

Frequent mount/unmount:
  • effects re-run
  • subscriptions recreated
Fix:
  • cleanup properly
  • avoid unnecessary unmounting

❌ Weak Answer

β€œReact handles memory automatically.” πŸ‘‰ Dangerous assumption

15. How do you design conditional rendering for large dynamic UIs (e.g., dashboards)?

πŸ” Follow-up

  • How do you keep it scalable?

βœ… Strong Answer

Use config-driven rendering:
const map = { admin: [A, B], user: [A] };
Render via .map()

❌ Weak Answer

β€œUse multiple if-else.” πŸ‘‰ Not scalable

16. What issues arise from nested conditional rendering in real apps?

πŸ” Follow-up

  • How do you refactor?

βœ… Strong Answer

Problems:
  • unreadable
  • hard to debug
Fix:
  • extract functions
  • use maps/configs

❌ Weak Answer

β€œIt’s fine if it works.” πŸ‘‰ Poor maintainability mindset

17. How does conditional rendering affect animations?

πŸ” Follow-up

  • How to fix animation reset?

βœ… Strong Answer

Unmounting resets animation:
{isVisible && <Anim />}
Fix:
  • control via props instead of mount

❌ Weak Answer

β€œUse CSS animations.” πŸ‘‰ Doesn’t address remount issue

18. How would you conditionally render components without causing unnecessary re-renders?

πŸ” Follow-up

  • Role of memoization?

βœ… Strong Answer

  • Use React.memo
  • Avoid recreating components
  • Keep stable references

❌ Weak Answer

β€œReact is fast enough.” πŸ‘‰ Not production mindset

19. How do you handle conditional rendering in lists with dynamic data?

πŸ” Follow-up

  • Why are keys important?

βœ… Strong Answer

  • Filter before map:
items.filter(...).map(...)
  • Use stable keys

❌ Weak Answer

β€œJust use index as key.” πŸ‘‰ Causes reconciliation bugs

20. Design a system to handle multiple conditional UI layers (auth, role, feature, data)

πŸ” Follow-up

  • How do you avoid spaghetti logic?

βœ… Strong Answer

Layer conditions:
if (!auth) return <Login />;
if (!role) return <Forbidden />;
if (!feature) return null;
return <UI />;
Or use composed wrappers.

❌ Weak Answer

β€œCombine all conditions in one expression.” πŸ‘‰ Leads to unreadable code

πŸ“Œ Final Insight

Senior-level understanding of conditional rendering means:
  • Thinking in lifecycle + reconciliation
  • Making intentional trade-offs
  • Designing scalable UI logic
  • Anticipating edge cases & bugs