> ## Documentation Index
> Fetch the complete documentation index at: https://docs.anujpandey.in/llms.txt
> Use this file to discover all available pages before exploring further.

# Conditional rendering

# 📘 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.

```jsx theme={null}
{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:

```jsx theme={null}
{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:

| Value       | Rendered? |
| ----------- | --------- |
| `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:

```jsx theme={null}
const [isOpen, setIsOpen] = useState(false);
```

#### 2. Props

Conditional rendering based on parent data:

```jsx theme={null}
{user.isAdmin && <AdminPanel />}
```

#### 3. Lists & Keys

Used with `.map()`:

```jsx theme={null}
items.length > 0 ? items.map(...) : <EmptyState />
```

#### 4. Hooks & Effects

Conditional rendering often depends on async data:

```jsx theme={null}
useEffect(() => {
  fetchData();
}, []);
```

***

## 3. Syntax & Examples

### 🔹 1. if / else (Outside JSX)

Best for complex logic.

```jsx theme={null}
function App() {
  const isLoggedIn = true;

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

***

### 🔹 2. Ternary Operator (Most Common)

Inline condition:

```jsx theme={null}
{isLoggedIn ? <Dashboard /> : <Login />}
```

#### Variation:

```jsx theme={null}
{isLoading ? <Loader /> : <Content />}
```

***

### 🔹 3. Logical AND (&&)

Render only if condition is true:

```jsx theme={null}
{isVisible && <Modal />}
```

#### Variation:

```jsx theme={null}
{items.length > 0 && <List items={items} />}
```

***

### 🔹 4. Logical OR (||)

Fallback rendering:

```jsx theme={null}
{username || "Guest"}
```

***

### 🔹 5. Switch Case Pattern

Used for multiple conditions:

```jsx theme={null}
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

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

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

***

### 🔹 7. Rendering Null (Hide Component)

```jsx theme={null}
{isHidden ? null : <Component />}
```

***

### 🔹 8. Inline IIFE (Advanced)

```jsx theme={null}
{
  (() => {
    if (isLoggedIn) return <Dashboard />;
    return <Login />;
  })()
}
```

***

### 🔹 9. Multiple Conditions

```jsx theme={null}
{isLoggedIn && isAdmin && <AdminPanel />}
```

***

### 🔹 10. Conditional CSS (Indirect Rendering)

```jsx theme={null}
<div className={isActive ? "active" : "inactive"} />
```

***

## 4. Edge Cases / Common Mistakes

### ⚠️ 1. Rendering `0` Accidentally

```jsx theme={null}
{items.length && <List />}
```

❌ If `length = 0`, React renders `0`

✅ Fix:

```jsx theme={null}
{items.length > 0 && <List />}
```

***

### ⚠️ 2. Nested Ternary Hell

```jsx theme={null}
{a ? (b ? <X /> : <Y />) : <Z />}
```

❌ Hard to read and maintain

✅ Use helper functions or variables

***

### ⚠️ 3. Returning Undefined

```jsx theme={null}
if (condition) {
  return;
}
```

❌ React expects JSX or `null`

***

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

```jsx theme={null}
{count && <Badge />}
```

If `count = 0`, it renders `0`

***

### ⚠️ 5. Component State Reset on Conditional Mount

```jsx theme={null}
{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

```jsx theme={null}
{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

```jsx theme={null}
{isLoggedIn ? <Dashboard /> : <Login />}
```

***

### ✅ 2. Use `&&` for Simple Visibility

```jsx theme={null}
{isOpen && <Modal />}
```

***

### ✅ 3. Extract Complex Logic

```jsx theme={null}
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

```jsx theme={null}
if (loading) return <Loader />;
if (error) return <Error />;
return <Data />;
```

***

### ✅ 6. Be Careful with Truthy/Falsy Values

Always explicitly check:

```jsx theme={null}
{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)

```jsx theme={null}
<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:

```jsx theme={null}
{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:

```jsx theme={null}
<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

```jsx theme={null}
{isOpen && <Modal />}
```

✔ Clean and concise
❌ Only works for "render or nothing"
❌ Can introduce bugs with falsy values (`0`, `""`)

***

### Ternary Operator

```jsx theme={null}
{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`**.

```jsx theme={null}
{0 && <Component />}
```

JavaScript evaluates:

```js theme={null}
0 && <Component /> // returns 0
```

React then renders `0`.

***

### ✅ Fix

```jsx theme={null}
{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.

```jsx theme={null}
{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

```jsx theme={null}
const [formData, setFormData] = useState({});
```

#### 2. Keep Component Mounted

```jsx theme={null}
<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

```jsx theme={null}
{isHeavyVisible && <HeavyComponent />}
```

✔ Avoids rendering expensive components

***

### 🐌 Hurt performance

If toggled frequently:

* Mount/unmount cycles
* Re-running effects
* Recreating DOM nodes

***

### ⚖️ Trade-off Strategy

| Scenario           | Approach           |
| ------------------ | ------------------ |
| Rarely shown       | Conditional render |
| Frequently toggled | Hide with CSS      |

***

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

### ✅ Answer

Avoid nested ternaries:

```jsx theme={null}
{loading ? <Loader /> : error ? <Error /> : <Data />}
```

***

### ✅ Better Approach

```jsx theme={null}
if (loading) return <Loader />;
if (error) return <Error />;
return <Data />;
```

***

### 💡 Why?

* Improves readability
* Easier to debug
* Scales better

***

### 🔁 Alternative Pattern

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

return renderMap[status];
```

***

## 7. What problems arise from nested conditional rendering?

### ✅ Answer

```jsx theme={null}
{a ? (b ? <X /> : <Y />) : <Z />}
```

### ❌ Issues

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

***

### ✅ Solution

Extract logic:

```jsx theme={null}
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:

```jsx theme={null}
{isVisible && items.map(item => <Item />)}
```

Without keys:

* React cannot track identity
* Leads to incorrect DOM updates

***

### ✅ Correct

```jsx theme={null}
{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

```jsx theme={null}
return null;
```

✔ Component renders nothing
✔ Lifecycle still runs

***

### ❗ Important Distinction

| Case               | Behavior                   |
| ------------------ | -------------------------- |
| `return null`      | Component exists, no UI    |
| Conditional render | Component 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

```jsx theme={null}
<div style={{ minHeight: 200 }}>
  {isLoading ? <Loader /> : <Content />}
</div>
```

#### 2. Skeleton loaders

```jsx theme={null}
{isLoading ? <Skeleton /> : <Content />}
```

***

### 💡 Why?

Improves UX and avoids visual jank.

***

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

### ✅ Answer

```jsx theme={null}
<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

```jsx theme={null}
{isActive ? <Button /> : <Button />}
```

***

### ✅ Better

```jsx theme={null}
<Button className={isActive ? "active" : ""} />
```

***

### 💡 Insight

Avoid unnecessary DOM churn.

***

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

### ✅ Answer

```jsx theme={null}
{isVisible && <ExpensiveComponent />}
```

Each time `isVisible` toggles:

* Component recreated
* Effects rerun

***

### ✅ Optimization

```jsx theme={null}
const Memoized = React.memo(ExpensiveComponent);
```

***

### 💡 Insight

Conditional rendering affects **component identity**.

***

## 14. What are the risks of conditional hooks usage?

### ✅ Answer

❌ Invalid:

```jsx theme={null}
if (isVisible) {
  useEffect(() => {});
}
```

***

### 🔥 Why?

Hooks must run **in the same order every render**.

***

### ✅ Fix

```jsx theme={null}
useEffect(() => {
  if (isVisible) {
    // logic
  }
}, [isVisible]);
```

***

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

### ✅ Answer

```jsx theme={null}
{features.newDashboard ? <NewDashboard /> : <OldDashboard />}
```

***

### 🔍 Real-world considerations:

* Remote config
* A/B testing
* Gradual rollout

***

### ⚖️ Alternative

Feature wrapper:

```jsx theme={null}
<Feature flag="newDashboard">
  <NewDashboard />
</Feature>
```

***

## 16. How does conditional rendering impact accessibility?

### ✅ Answer

Removing elements:

```jsx theme={null}
{isOpen && <Modal />}
```

* Removes from DOM → screen readers can't access

***

### ✅ Alternative

```jsx theme={null}
<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

```jsx theme={null}
console.log("render", isVisible);
```

3. Use React DevTools:

   * Inspect mount/unmount
4. 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

```jsx theme={null}
{isOpen && <Modal />}
```

✔ Simple cases

***

### Extracted

```jsx theme={null}
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?**

```jsx theme={null}
{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?**

```jsx theme={null}
{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?**

```jsx theme={null}
{"" && <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.

```jsx theme={null}
{isOpen && <Modal />}
```

B.

```jsx theme={null}
{isOpen ? <Modal /> : null}
```

C.

```jsx theme={null}
<Modal hidden={!isOpen} />
```

D.

```jsx theme={null}
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?**

```jsx theme={null}
{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.

```jsx theme={null}
<div>{isLoading && <Loader />}</div>
```

B.

```jsx theme={null}
<div style={{ minHeight: 200 }}>
  {isLoading ? <Loader /> : <Content />}
</div>
```

C.

```jsx theme={null}
<Loader />
```

D.

```jsx theme={null}
{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?**

```jsx theme={null}
{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.

```jsx theme={null}
{loading ? <A /> : error ? <B /> : <C />}
```

B.

```jsx theme={null}
if (loading) return <A />;
if (error) return <B />;
return <C />;
```

C.

```jsx theme={null}
loading && <A />
error && <B />
```

D.

```jsx theme={null}
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?**

```jsx theme={null}
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?**

```jsx theme={null}
{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.

```jsx theme={null}
{isOpen && <Heavy />}
```

B.

```jsx theme={null}
{isOpen ? <Heavy /> : <></>}
```

C.

```jsx theme={null}
<Heavy style={{ display: isOpen ? "block" : "none" }} />
```

D.

```jsx theme={null}
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?**

```jsx theme={null}
{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.

```jsx theme={null}
if (flag) return <New />
```

B.

```jsx theme={null}
{flag ? <New /> : <Old />}
```

C.

```jsx theme={null}
flag && <New />
```

D.

```jsx theme={null}
<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?**

```jsx theme={null}
{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.

```jsx theme={null}
{isOpen && <Modal />}
```

B.

```jsx theme={null}
<Modal aria-hidden={!isOpen} />
```

C.

```jsx theme={null}
<Modal />
```

D.

```jsx theme={null}
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?**

```jsx theme={null}
{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

```jsx theme={null}
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

```jsx theme={null}
function Feature({ flag, children, fallback }) {
  return flag ? children : fallback;
}
```

Usage:

```jsx theme={null}
<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

```jsx theme={null}
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

```jsx theme={null}
{isVisible && <Form />}
```

***

### ✅ Correct

```jsx theme={null}
<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

```jsx theme={null}
{items.length && <List />}
```

***

### ✅ Solution

```jsx theme={null}
{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

```jsx theme={null}
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

```jsx theme={null}
const layoutMap = {
  grid: <GridView />,
  list: <ListView />,
};

return layoutMap[layout];
```

***

## 🧩 Problem 8: Prevent Layout Shift (Skeleton Loader)

### 📌 Problem Statement

Avoid UI jump during loading.

***

### ✅ Solution

```jsx theme={null}
<div style={{ minHeight: 200 }}>
  {loading ? <Skeleton /> : <Content />}
</div>
```

***

## 🧩 Problem 9: Multi-Step Form Rendering

### 📌 Problem Statement

Render steps based on current index.

***

### ✅ Solution

```jsx theme={null}
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

```jsx theme={null}
<Modal isOpen={isOpen} />
```

Inside Modal:

```jsx theme={null}
return (
  <div style={{ display: isOpen ? "block" : "none" }}>
    {/* content */}
  </div>
);
```

***

## 🧩 Problem 11: A/B Testing UI

### 📌 Problem Statement

Render UI variant based on experiment.

***

### ✅ Solution

```jsx theme={null}
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

```jsx theme={null}
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

```jsx theme={null}
<Suspense fallback={<Loader />}>
  {isVisible && <LazyComponent />}
</Suspense>
```

***

## 🧩 Problem 14: Conditional Wrapper Component

### 📌 Problem Statement

Wrap content only if condition is true.

***

### ✅ Solution

```jsx theme={null}
function ConditionalWrapper({ condition, wrapper, children }) {
  return condition ? wrapper(children) : children;
}
```

Usage:

```jsx theme={null}
<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

```jsx theme={null}
{hasError ? <Fallback /> : <Component />}
```

***

## 🧩 Problem 16: Conditional Animation Mount

### 📌 Problem Statement

Animate component only when entering.

***

### ✅ Solution

```jsx theme={null}
{isVisible && <AnimatedComponent />}
```

### Edge Case

* Animation reset on remount

***

## 🧩 Problem 17: Render Different Components Based on Screen Size

### 📌 Problem Statement

Mobile vs Desktop rendering.

***

### ✅ Solution

```jsx theme={null}
return isMobile ? <MobileView /> : <DesktopView />;
```

***

## 🧩 Problem 18: Debounced Conditional Rendering

### 📌 Problem Statement

Render search results only after debounce.

***

### ✅ Solution

```jsx theme={null}
{debouncedQuery && <Results />}
```

***

## 🧩 Problem 19: Conditional Rendering with Memoization

### 📌 Problem Statement

Avoid re-render of heavy component.

***

### ✅ Solution

```jsx theme={null}
const MemoComp = React.memo(Heavy);

return isVisible && <MemoComp />;
```

***

## 🧩 Problem 20: Progressive Disclosure UI

### 📌 Problem Statement

Show more content when user clicks "Show More".

***

### ✅ Solution

```jsx theme={null}
{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

```jsx theme={null}
{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

```jsx theme={null}
{items.length > 0 && <List items={items} />}
```

### 🧠 Best Practice

Always explicitly check numeric conditions.

***

## 🧩 2. State Reset on Toggle

### ❌ Buggy Code

```jsx theme={null}
{isOpen && <Form />}
```

### 🔍 What’s Wrong?

Form input resets when toggled.

### 💡 Why It Happens

Component is unmounted → state lost.

### ✅ Fixed Code

```jsx theme={null}
<Form style={{ display: isOpen ? "block" : "none" }} />
```

### 🧠 Best Practice

Avoid unmounting when state persistence is needed.

***

## 🧩 3. Nested Ternary Logic Bug

### ❌ Buggy Code

```jsx theme={null}
{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

```jsx theme={null}
if (!isAdmin) return <C />;
return isActive ? <A /> : <B />;
```

### 🧠 Best Practice

Avoid nested ternaries beyond one level.

***

## 🧩 4. Component Re-Mount Performance Issue

### ❌ Buggy Code

```jsx theme={null}
{showChart && <HeavyChart data={data} />}
```

### 🔍 What’s Wrong?

Chart re-initializes on every toggle.

### 💡 Why It Happens

Unmount → remount → expensive setup runs again.

### ✅ Fixed Code

```jsx theme={null}
<HeavyChart hidden={!showChart} data={data} />
```

### 🧠 Best Practice

Keep expensive components mounted if frequently toggled.

***

## 🧩 5. Conditional Hook Execution

### ❌ Buggy Code

```jsx theme={null}
if (isVisible) {
  useEffect(() => {
    fetchData();
  }, []);
}
```

### 🔍 What’s Wrong?

Breaks React hook rules.

### 💡 Why It Happens

Hooks must run in consistent order every render.

### ✅ Fixed Code

```jsx theme={null}
useEffect(() => {
  if (isVisible) {
    fetchData();
  }
}, [isVisible]);
```

### 🧠 Best Practice

Never call hooks conditionally.

***

## 🧩 6. Missing Fallback UI

### ❌ Buggy Code

```jsx theme={null}
{isEnabled && <Feature />}
```

### 🔍 What’s Wrong?

Nothing renders when disabled → confusing UX.

### 💡 Why It Happens

No fallback branch defined.

### ✅ Fixed Code

```jsx theme={null}
{isEnabled ? <Feature /> : <Fallback />}
```

### 🧠 Best Practice

Always define fallback for critical UI.

***

## 🧩 7. Incorrect OR Usage

### ❌ Buggy Code

```jsx theme={null}
{username || <Guest />}
```

### 🔍 What’s Wrong?

If `username = "0"` or `"false"` → unexpected render.

### 💡 Why It Happens

JS truthy/falsy confusion.

### ✅ Fixed Code

```jsx theme={null}
{username ? username : <Guest />}
```

### 🧠 Best Practice

Avoid relying on implicit truthiness for UI.

***

## 🧩 8. Flickering UI Due to Rapid Toggle

### ❌ Buggy Code

```jsx theme={null}
{loading && <Spinner />}
{!loading && <Content />}
```

### 🔍 What’s Wrong?

Flickering during quick state transitions.

### 💡 Why It Happens

Two separate conditions → race conditions in render.

### ✅ Fixed Code

```jsx theme={null}
{loading ? <Spinner /> : <Content />}
```

### 🧠 Best Practice

Use a single conditional branch.

***

## 🧩 9. Key Misuse in Conditional List

### ❌ Buggy Code

```jsx theme={null}
{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

```jsx theme={null}
items.map(item => <Item key={item.id} />)
```

### 🧠 Best Practice

Never use index as key in dynamic lists.

***

## 🧩 10. Returning Undefined

### ❌ Buggy Code

```jsx theme={null}
if (!data) return;
```

### 🔍 What’s Wrong?

React expects JSX or `null`.

### 💡 Why It Happens

Returning `undefined` is not valid render output.

### ✅ Fixed Code

```jsx theme={null}
if (!data) return null;
```

### 🧠 Best Practice

Always return `null` for empty render.

***

## 🧩 11. Duplicate Rendering Conditions

### ❌ Buggy Code

```jsx theme={null}
{isOpen && <Modal />}
{isOpen && <Backdrop />}
```

### 🔍 What’s Wrong?

Logic duplicated → harder to maintain.

### 💡 Why It Happens

Conditions scattered.

### ✅ Fixed Code

```jsx theme={null}
{isOpen && (
  <>
    <Backdrop />
    <Modal />
  </>
)}
```

### 🧠 Best Practice

Group related conditional UI.

***

## 🧩 12. Layout Shift Issue

### ❌ Buggy Code

```jsx theme={null}
{isLoading ? <Loader /> : <Content />}
```

### 🔍 What’s Wrong?

Content jumps when loader disappears.

### 💡 Why It Happens

Different component sizes.

### ✅ Fixed Code

```jsx theme={null}
<div style={{ minHeight: 200 }}>
  {isLoading ? <Loader /> : <Content />}
</div>
```

### 🧠 Best Practice

Reserve layout space.

***

## 🧩 13. Conditional Rendering Inside Map

### ❌ Buggy Code

```jsx theme={null}
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

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

### 🧠 Best Practice

Filter before mapping.

***

## 🧩 14. Wrong Conditional Wrapper

### ❌ Buggy Code

```jsx theme={null}
{isLink && <a><Button /></a>}
{!isLink && <Button />}
```

### 🔍 What’s Wrong?

Duplicate JSX.

### 💡 Why It Happens

Wrapper logic not abstracted.

### ✅ Fixed Code

```jsx theme={null}
const Wrapper = isLink ? "a" : React.Fragment;

<Wrapper>
  <Button />
</Wrapper>
```

### 🧠 Best Practice

Use conditional wrappers.

***

## 🧩 15. Expensive Computation on Every Render

### ❌ Buggy Code

```jsx theme={null}
{isVisible && <Chart data={computeData()} />}
```

### 🔍 What’s Wrong?

`computeData()` runs every render.

### 💡 Why It Happens

Function executes before condition check.

### ✅ Fixed Code

```jsx theme={null}
{isVisible && <Chart data={memoizedData} />}
```

### 🧠 Best Practice

Memoize expensive computations.

***

## 🧩 16. Incorrect Default Case Handling

### ❌ Buggy Code

```jsx theme={null}
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

```jsx theme={null}
return map[status] || <Fallback />;
```

### 🧠 Best Practice

Always handle unknown states.

***

## 🧩 17. Multiple Conditions Causing Hidden Bugs

### ❌ Buggy Code

```jsx theme={null}
{isLoggedIn && isAdmin && <Panel />}
```

### 🔍 What’s Wrong?

No feedback if condition fails.

### 💡 Why It Happens

Silent failure → bad UX.

### ✅ Fixed Code

```jsx theme={null}
if (!isLoggedIn) return <Login />;
if (!isAdmin) return <Forbidden />;
return <Panel />;
```

### 🧠 Best Practice

Make failure states explicit.

***

## 🧩 18. Conditional Rendering Breaking Animation

### ❌ Buggy Code

```jsx theme={null}
{isVisible && <FadeIn />}
```

### 🔍 What’s Wrong?

Animation restarts every mount.

### 💡 Why It Happens

Component recreated each time.

### ✅ Fixed Code

```jsx theme={null}
<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:

```js theme={null}
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

```jsx theme={null}
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

```js theme={null}
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

***

## 🧩 15. Conditional Wrapper (Link vs Button)

### 📌 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**.

```jsx theme={null}
{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:

```jsx theme={null}
<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`.

```jsx theme={null}
{count && <Badge />}
```

Fix:

```jsx theme={null}
{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**:

```jsx theme={null}
if (loading) return <Loader />;
if (error) return <Error />;
return <Data />;
```

Or:

```jsx theme={null}
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:

```jsx theme={null}
{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**:

```jsx theme={null}
{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

```jsx theme={null}
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:

```jsx theme={null}
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

```jsx theme={null}
<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:

```jsx theme={null}
{isOpen && <Modal />}
```

* Screen readers lose access

Use:

```jsx theme={null}
<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:

```jsx theme={null}
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:

```jsx theme={null}
{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:

```jsx theme={null}
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:

```jsx theme={null}
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**

***
