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

# Component composition

## 📘 Component Composition in React — Complete Theory Guide

***

# 1. Introduction

### 🔹 What is Component Composition?

**Component composition** is a pattern in React where you build complex UIs by **combining smaller, reusable components together**.

Instead of inheritance, React promotes:

> 👉 *“Build components using other components”*

```jsx theme={null}
function Layout({ children }) {
  return <div className="layout">{children}</div>;
}

function App() {
  return (
    <Layout>
      <h1>Hello</h1>
      <p>Welcome</p>
    </Layout>
  );
}
```

Here, `Layout` is composed with child elements.

***

### 🔹 Why is it Important in React?

* Encourages **reusability**
* Improves **maintainability**
* Promotes **separation of concerns**
* Aligns with React’s **declarative model**

React is fundamentally built around composition rather than inheritance.

***

### 🔹 When & Why We Use It

Use component composition when:

* Building **layouts** (headers, sidebars, cards)
* Creating **reusable UI patterns**
* Sharing behavior without inheritance
* Avoiding **prop drilling complexity**
* Designing flexible APIs for components

***

# 2. Concepts / Internal Workings

***

## 🔹 2.1 Composition vs Inheritance

React avoids inheritance because:

* It creates tight coupling
* Harder to scale and refactor

Instead, React uses:

```jsx theme={null}
<ComponentA>
  <ComponentB />
</ComponentA>
```

***

## 🔹 2.2 The `children` Prop

At the core of composition is `children`.

```jsx theme={null}
function Card({ children }) {
  return <div className="card">{children}</div>;
}
```

Usage:

```jsx theme={null}
<Card>
  <h2>Title</h2>
  <p>Description</p>
</Card>
```

👉 Internally:

* React passes everything inside `<Card>` as `props.children`
* It can be:

  * JSX
  * Arrays
  * Functions
  * Strings

***

## 🔹 2.3 Containment Pattern

Used when components act as **containers**.

```jsx theme={null}
function Modal({ children }) {
  return <div className="modal">{children}</div>;
}
```

***

## 🔹 2.4 Specialization Pattern

Creating specific components using generic ones.

```jsx theme={null}
function Button({ children }) {
  return <button>{children}</button>;
}

function PrimaryButton() {
  return <Button>Primary</Button>;
}
```

***

## 🔹 2.5 Multiple Slots (Advanced Composition)

Sometimes we need multiple "holes":

```jsx theme={null}
function Layout({ header, footer, children }) {
  return (
    <>
      <header>{header}</header>
      <main>{children}</main>
      <footer>{footer}</footer>
    </>
  );
}
```

Usage:

```jsx theme={null}
<Layout
  header={<h1>Header</h1>}
  footer={<p>Footer</p>}
>
  <p>Content</p>
</Layout>
```

***

## 🔹 2.6 Function as Children (Render Props)

A powerful composition pattern:

```jsx theme={null}
function DataFetcher({ children }) {
  const data = { name: "John" };
  return children(data);
}

<DataFetcher>
  {(data) => <p>{data.name}</p>}
</DataFetcher>
```

***

## 🔹 2.7 Compound Components Pattern

Components work together as a group:

```jsx theme={null}
function Tabs({ children }) {
  return <div>{children}</div>;
}

Tabs.Tab = function Tab({ children }) {
  return <button>{children}</button>;
};

<Tabs>
  <Tabs.Tab>Tab 1</Tabs.Tab>
  <Tabs.Tab>Tab 2</Tabs.Tab>
</Tabs>
```

***

## 🔹 2.8 How It Works Internally in React

* JSX is transformed into **React elements (objects)**
* `children` becomes part of `props`
* During reconciliation:

  * React builds a **component tree**
  * Each composed component becomes a node
* React efficiently updates only changed nodes

👉 Composition does NOT create deep inheritance chains — just nested trees.

***

## 🔹 2.9 Relationship with Other React Features

### ✔ Props

* Composition heavily relies on props (especially `children`)

### ✔ State

* State can be lifted or shared across composed components

### ✔ Context API

* Helps avoid prop drilling in deeply composed trees

### ✔ Hooks

* Composition + hooks = reusable logic

***

# 3. Syntax & Examples

***

## 🔹 3.1 Basic Composition

```jsx theme={null}
function Wrapper({ children }) {
  return <div className="wrapper">{children}</div>;
}

function App() {
  return (
    <Wrapper>
      <h1>Hello</h1>
    </Wrapper>
  );
}
```

***

## 🔹 3.2 Reusable Card Component

```jsx theme={null}
function Card({ title, children }) {
  return (
    <div className="card">
      <h2>{title}</h2>
      {children}
    </div>
  );
}

<Card title="User">
  <p>Name: John</p>
</Card>
```

***

## 🔹 3.3 Layout Composition

```jsx theme={null}
function PageLayout({ sidebar, content }) {
  return (
    <div className="layout">
      <aside>{sidebar}</aside>
      <main>{content}</main>
    </div>
  );
}

<PageLayout
  sidebar={<p>Menu</p>}
  content={<p>Main Content</p>}
/>
```

***

## 🔹 3.4 Wrapper for Styling

```jsx theme={null}
function Box({ children }) {
  return <div style={{ padding: "10px" }}>{children}</div>;
}
```

***

## 🔹 3.5 Render Props Example

```jsx theme={null}
function Toggle({ children }) {
  const [on, setOn] = React.useState(false);
  return children(on, () => setOn(!on));
}

<Toggle>
  {(on, toggle) => (
    <button onClick={toggle}>
      {on ? "ON" : "OFF"}
    </button>
  )}
</Toggle>
```

***

## 🔹 3.6 Compound Components Example

```jsx theme={null}
function Accordion({ children }) {
  return <div>{children}</div>;
}

Accordion.Item = function ({ title, children }) {
  return (
    <div>
      <h3>{title}</h3>
      <div>{children}</div>
    </div>
  );
};

<Accordion>
  <Accordion.Item title="Q1">Answer</Accordion.Item>
</Accordion>
```

***

# 4. Edge Cases / Common Mistakes

***

## ⚠️ 4.1 Forgetting to Render `children`

```jsx theme={null}
function Box({ children }) {
  return <div></div>; // ❌ children ignored
}
```

👉 Fix:

```jsx theme={null}
return <div>{children}</div>;
```

***

## ⚠️ 4.2 Over-Composition

Too many layers:

```jsx theme={null}
<A>
  <B>
    <C>
      <D />
    </C>
  </B>
</A>
```

❌ Leads to:

* Hard debugging
* Poor readability

***

## ⚠️ 4.3 Prop Drilling Instead of Composition

```jsx theme={null}
<Parent data={data}>
  <Child data={data}>
```

👉 Instead:

* Use composition or context

***

## ⚠️ 4.4 Misusing Render Props

```jsx theme={null}
<Data>{data}</Data> // ❌ not a function
```

👉 Should be:

```jsx theme={null}
<Data>{(data) => <div>{data}</div>}</Data>
```

***

## ⚠️ 4.5 Breaking Encapsulation

Passing too much control:

```jsx theme={null}
<Component internalStateSetter={setState} />
```

❌ Exposes internals

***

## ⚠️ 4.6 Key Issues in Composed Lists

```jsx theme={null}
{items.map(item => (
  <Card>{item.name}</Card> // ❌ missing key
))}
```

***

# 5. Best Practices

***

## ✅ 5.1 Prefer Composition Over Inheritance

* Always favor **composition-first design**

***

## ✅ 5.2 Keep Components Small & Focused

Each component should:

* Do one thing well
* Be easily composable

***

## ✅ 5.3 Use Clear Component APIs

Bad:

```jsx theme={null}
<Component data1 data2 data3 />
```

Better:

```jsx theme={null}
<Layout header={...} footer={...} />
```

***

## ✅ 5.4 Avoid Deep Nesting

Flatten when possible:

```jsx theme={null}
<Layout>
  <Header />
  <Content />
</Layout>
```

***

## ✅ 5.5 Combine Composition with Hooks

```jsx theme={null}
function useToggle() {
  const [on, setOn] = useState(false);
  return { on, toggle: () => setOn(!on) };
}
```

***

## ✅ 5.6 Memoization for Performance

Use:

* `React.memo`
* `useMemo`
* `useCallback`

When:

* Components are deeply composed
* Props rarely change

***

## ✅ 5.7 Use Compound Components for Complex UI

Ideal for:

* Tabs
* Accordions
* Dropdowns

***

## ✅ 5.8 Use Context to Avoid Prop Drilling

```jsx theme={null}
const ThemeContext = React.createContext();
```

***

## ✅ 5.9 Keep Composition Predictable

* Avoid hidden side effects
* Keep data flow clear

***

# 🔚 Summary

Component composition is the **core philosophy of React**:

* Build small → Combine → Scale
* Prefer flexibility over rigid hierarchies
* Enables powerful patterns like:

  * Render props
  * Compound components
  * Layout systems

***

## 📘 Advanced Interview Questions — Component Composition (React)

***

# 1. What problem does component composition solve that inheritance cannot in React?

### ✅ Strong Answer

Composition solves **flexibility and decoupling** problems that inheritance introduces.

* Inheritance creates **tight coupling** between parent-child classes
* Leads to rigid hierarchies and difficult refactoring
* React instead uses **tree-based composition**

👉 With composition:

```jsx theme={null}
<Layout>
  <Sidebar />
  <Content />
</Layout>
```

Each component is:

* Independent
* Replaceable
* Reusable

### 💡 Why this matters

React’s reconciliation works on a **tree of elements**, not class hierarchies. Composition maps naturally to this model.

### 🔁 Alternative

* Inheritance → rigid, static
* Composition → dynamic, runtime flexibility

***

# 2. How does React internally handle `children` during reconciliation?

### ✅ Strong Answer

* `children` is just a **prop**
* During JSX transformation:

```jsx theme={null}
<Card>
  <p>Hello</p>
</Card>
```

becomes:

```js theme={null}
React.createElement(Card, null, React.createElement('p', null, 'Hello'));
```

👉 Internally:

* `children` is stored inside `props.children`
* React builds a **fiber tree**
* Each child becomes a **fiber node**

### 💡 Key Insight

React does **not treat children specially after creation** — they’re just part of the props tree.

### ⚠️ Pitfall

If children change structure:

* React diffing depends on **keys + order**
* Can cause unnecessary re-renders

***

# 3. Why is composition preferred over prop drilling for deep component trees?

### ✅ Strong Answer

Prop drilling creates:

* Tight coupling across layers
* Hard-to-maintain APIs
* Increased re-render surface

```jsx theme={null}
<Parent data={data}>
  <Child data={data}>
    <GrandChild data={data} />
  </Child>
</Parent>
```

👉 With composition:

```jsx theme={null}
<Parent>
  <GrandChild data={data} />
</Parent>
```

### 💡 Why it works

* Data stays closer to where it’s needed
* Intermediate components become **agnostic wrappers**

### 🔁 Alternative

* Context API for global/shared state
* Composition for **structural flexibility**

***

# 4. What are the trade-offs between `children`-based composition and explicit props (slots)?

### ✅ Strong Answer

### Option 1: `children`

```jsx theme={null}
<Card>
  <Header />
  <Body />
</Card>
```

✔ Flexible
❌ Implicit structure (harder to enforce)

***

### Option 2: Named slots

```jsx theme={null}
<Card header={<Header />} body={<Body />} />
```

✔ Explicit
✔ Easier validation
❌ Slightly verbose

***

### 💡 Trade-off Summary

| Approach | Flexibility | Readability | Control |
| -------- | ----------- | ----------- | ------- |
| children | High        | Medium      | Low     |
| slots    | Medium      | High        | High    |

👉 Senior engineers choose based on:

* API clarity
* Design constraints

***

# 5. Explain the Compound Component pattern and its internal coordination mechanism.

### ✅ Strong Answer

Compound components share **implicit state via context**.

```jsx theme={null}
const TabsContext = React.createContext();

function Tabs({ children }) {
  const [active, setActive] = useState(0);

  return (
    <TabsContext.Provider value={{ active, setActive }}>
      {children}
    </TabsContext.Provider>
  );
}
```

Child components consume it:

```jsx theme={null}
function Tab({ index, children }) {
  const { active, setActive } = useContext(TabsContext);

  return (
    <button onClick={() => setActive(index)}>
      {children}
    </button>
  );
}
```

### 💡 Why this works

* Avoids prop drilling
* Keeps API clean:

```jsx theme={null}
<Tabs>
  <Tab index={0}>Tab 1</Tab>
</Tabs>
```

### ⚠️ Trade-off

* Hidden coupling via context
* Harder to debug than explicit props

***

# 6. When would you avoid using composition and prefer a custom hook instead?

### ✅ Strong Answer

Use hooks when sharing **logic**, not UI.

❌ Composition misuse:

```jsx theme={null}
<Toggle>
  {(on) => <Component on={on} />}
</Toggle>
```

✔ Better:

```jsx theme={null}
const { on, toggle } = useToggle();
```

### 💡 Rule

* Composition → UI structure
* Hooks → logic reuse

***

# 7. What are the performance implications of deeply composed component trees?

### ✅ Strong Answer

Deep composition can cause:

* More **fiber nodes**
* Increased reconciliation work
* Prop changes cascading downward

### Example

```jsx theme={null}
<A>
  <B>
    <C>
      <D />
    </C>
  </B>
</A>
```

### 💡 Optimization

* `React.memo`
* Avoid unnecessary re-renders
* Stable props with `useCallback`

### ⚠️ Insight

Depth alone isn't bad — **unstable props are the real issue**

***

# 8. How can composition lead to unnecessary re-renders, and how do you prevent it?

### ✅ Strong Answer

Problem:

```jsx theme={null}
<Wrapper>
  <Child data={{ value: 1 }} />
</Wrapper>
```

New object every render → re-render

### Fix:

```jsx theme={null}
const data = useMemo(() => ({ value: 1 }), []);
```

Or:

```jsx theme={null}
const Child = React.memo(...)
```

### 💡 Core Idea

Composition amplifies prop instability across tree levels.

***

# 9. What is the difference between render props and component composition?

### ✅ Strong Answer

### Render Props

```jsx theme={null}
<Data>
  {(data) => <UI data={data} />}
</Data>
```

* Dynamic rendering
* Logic-driven composition

***

### Composition

```jsx theme={null}
<Data>
  <UI />
</Data>
```

* Static structure

***

### 💡 Trade-off

| Pattern      | Flexibility | Complexity |
| ------------ | ----------- | ---------- |
| Composition  | Medium      | Low        |
| Render Props | High        | Higher     |

***

# 10. How do you enforce constraints in a highly composable API?

### ✅ Strong Answer

Problem:

```jsx theme={null}
<Card>
  <RandomComponent />
</Card>
```

No guarantees of structure.

### Solutions:

1. Runtime validation:

```jsx theme={null}
React.Children.forEach(children, child => {
  if (child.type !== AllowedComponent) {
    throw new Error("Invalid child");
  }
});
```

2. TypeScript constraints

3. Compound pattern enforcement

***

### 💡 Trade-off

* Flexibility vs Safety

***

# 11. Why can overusing composition hurt readability?

### ✅ Strong Answer

Excess nesting:

```jsx theme={null}
<A>
  <B>
    <C>
      <D />
    </C>
  </B>
</A>
```

### Issues:

* Hard tracing data flow
* Debug complexity
* Reduced clarity

### 💡 Fix

* Flatten structure
* Extract meaningful components

***

# 12. How does composition interact with Context API?

### ✅ Strong Answer

Context complements composition:

* Composition defines structure
* Context provides data access

```jsx theme={null}
<ThemeProvider>
  <Layout>
    <Button />
  </Layout>
</ThemeProvider>
```

### 💡 Insight

Without context:

* Deep composition → prop drilling

With context:

* Decoupled data access

***

# 13. What are “controlled vs uncontrolled” composition patterns?

### ✅ Strong Answer

### Controlled:

```jsx theme={null}
<Tabs active={active} onChange={setActive} />
```

Parent controls state

***

### Uncontrolled:

```jsx theme={null}
<Tabs defaultActive={0} />
```

Component manages state

***

### 💡 Trade-off

| Type         | Control | Complexity |
| ------------ | ------- | ---------- |
| Controlled   | High    | Higher     |
| Uncontrolled | Low     | Simpler    |

***

# 14. How do keys affect composed components?

### ✅ Strong Answer

Keys affect:

* Identity
* Reconciliation

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

### ⚠️ Pitfall

Wrong keys:

```jsx theme={null}
key={index}
```

→ causes:

* State bugs
* UI mismatches

***

# 15. How would you design a flexible layout system using composition?

### ✅ Strong Answer

```jsx theme={null}
<Layout>
  <Layout.Header />
  <Layout.Sidebar />
  <Layout.Content />
</Layout>
```

Internally:

* Uses context for layout coordination
* Uses slots for flexibility

### 💡 Why this design

* Declarative API
* Clear structure
* Scalable

***

# 16. When does composition break encapsulation?

### ✅ Strong Answer

If parent controls too much:

```jsx theme={null}
<Component setInternalState={setState} />
```

### Problem:

* Leaks internal logic
* Breaks abstraction

### 💡 Fix

Expose:

* Callbacks
* Controlled APIs

***

# 17. How does composition influence testability?

### ✅ Strong Answer

✔ Improves testability:

* Smaller units
* Easier mocking

```jsx theme={null}
render(<Card><MockChild /></Card>);
```

### ⚠️ But:

* Deep composition → harder integration tests

***

# 18. How do you debug issues in a deeply composed component tree?

### ✅ Strong Answer

Approach:

1. Trace props flow
2. Use React DevTools (component tree)
3. Check memoization issues
4. Inspect re-renders

### 💡 Senior Insight

Most bugs come from:

* Incorrect assumptions about composition boundaries
* Hidden coupling via context

***

# 🔚 Final Takeaway

Senior-level understanding of composition means:

* Knowing **when NOT to use it**
* Balancing **flexibility vs control**
* Understanding **how React internally processes trees**
* Designing **clean, scalable APIs**

***

## 📘 Advanced MCQs — Component Composition in React (Senior Level)

***

# 1. What will be rendered in this composition scenario?

```jsx theme={null}
function Wrapper({ children }) {
  return <div>{children}</div>;
}

function App() {
  return (
    <Wrapper>
      {null}
      {false}
      {"Hello"}
    </Wrapper>
  );
}
```

### Options:

A. Nothing renders
B. Only `"Hello"` renders
C. `null`, `false`, and `"Hello"` all render
D. React throws an error

### ✅ Correct Answer: B

### ✔ Explanation:

React ignores:

* `null`
* `false`
* `undefined`

Only valid renderable values like strings, numbers, and JSX are rendered.

👉 `"Hello"` is the only renderable child.

### ❌ Why others are wrong:

* A: Incorrect — `"Hello"` is rendered
* C: React does NOT render `null` or `false`
* D: No error occurs

***

# 2. What is the key issue in this composition pattern?

```jsx theme={null}
function Layout({ children }) {
  return <section>{children}</section>;
}

function App() {
  return (
    <Layout>
      {[<div>A</div>, <div>B</div>]}
    </Layout>
  );
}
```

### Options:

A. Invalid JSX syntax
B. Missing keys in children array
C. children cannot be arrays
D. Layout must use React.Children.map

### ✅ Correct Answer: B

### ✔ Explanation:

When rendering arrays:

```jsx theme={null}
[<div>A</div>, <div>B</div>]
```

React requires **keys** for stable reconciliation.

### ❌ Why others are wrong:

* A: Syntax is valid
* C: Arrays are allowed
* D: Not required, just optional utility

***

# 3. What happens when children change order without keys?

```jsx theme={null}
<>
  <Item name="A" />
  <Item name="B" />
</>
```

→ becomes:

```jsx theme={null}
<>
  <Item name="B" />
  <Item name="A" />
</>
```

### Options:

A. React re-renders both correctly
B. React swaps DOM nodes efficiently
C. State may get mixed between components
D. React throws warning and stops rendering

### ✅ Correct Answer: C

### ✔ Explanation:

Without keys:

* React uses **index-based reconciliation**
* Components may retain wrong state

👉 This leads to **state leakage bugs**

### ❌ Why others are wrong:

* A: Not guaranteed correct
* B: Incorrect — React cannot track identity
* D: Warning only, not a crash

***

# 4. What is the issue with this composition?

```jsx theme={null}
function Card({ children }) {
  return <div>{children}</div>;
}

<Card>
  <Header />
  <Footer />
</Card>
```

### Options:

A. Nothing is wrong
B. Order of children is not guaranteed
C. Card cannot accept multiple children
D. Header/Footer must be passed as props

### ✅ Correct Answer: A

### ✔ Explanation:

React preserves:

* Order
* Structure of children

This is a valid and common pattern.

### ❌ Why others are wrong:

* B: Order is preserved
* C: Multiple children allowed
* D: Not required

***

# 5. What is the subtle bug here?

```jsx theme={null}
function Wrapper({ children }) {
  return children;
}
```

### Options:

A. Wrapper must return a div
B. children must be cloned
C. Multiple children will cause an error
D. Nothing is wrong

### ✅ Correct Answer: D

### ✔ Explanation:

React allows returning:

* A single child
* Multiple children (as array)

No wrapper needed.

### ❌ Why others are wrong:

* A: Not required (Fragments exist)
* B: Cloning is optional
* C: Arrays are valid

***

# 6. What is problematic in this pattern?

```jsx theme={null}
function Parent({ children }) {
  return React.Children.only(children);
}
```

Usage:

```jsx theme={null}
<Parent>
  <Child1 />
  <Child2 />
</Parent>
```

### Options:

A. Only first child renders
B. Runtime error
C. Both children render
D. Warning only

### ✅ Correct Answer: B

### ✔ Explanation:

`React.Children.only` expects **exactly one child**

Multiple children → throws error

### ❌ Why others are wrong:

* A: It does not silently ignore
* C: Not allowed
* D: It throws, not warns

***

# 7. What happens in this render prop misuse?

```jsx theme={null}
function Data({ children }) {
  return children("data");
}

<Data>
  <div />
</Data>
```

### Options:

A. `<div />` renders normally
B. children is ignored
C. Runtime error
D. "data" is rendered

### ✅ Correct Answer: C

### ✔ Explanation:

`children` is expected to be a **function**, but it's a React element.

Calling it:

```js theme={null}
children("data")
```

→ TypeError

### ❌ Why others are wrong:

* A: Incorrect type
* B: It is executed, not ignored
* D: Function never runs

***

# 8. What is the issue with this composition?

```jsx theme={null}
function Modal({ children }) {
  return <div>{children}</div>;
}

<Modal>
  {() => <p>Hello</p>}
</Modal>
```

### Options:

A. Function will render automatically
B. Nothing renders
C. React throws error
D. Function is converted to string

### ✅ Correct Answer: B

### ✔ Explanation:

React does NOT execute functions passed as children unless explicitly called.

```jsx theme={null}
{children()} // required
```

### ❌ Why others are wrong:

* A: No automatic execution
* C: No error
* D: Functions are ignored, not stringified

***

# 9. Why is this composition inefficient?

```jsx theme={null}
<Wrapper>
  <Child config={{ a: 1 }} />
</Wrapper>
```

### Options:

A. config is invalid
B. Wrapper causes re-render
C. New object each render breaks memoization
D. children cannot accept objects

### ✅ Correct Answer: C

### ✔ Explanation:

Every render creates new object → breaks `React.memo`

### ❌ Why others are wrong:

* A: Valid object
* B: Not necessarily
* D: Objects allowed

***

# 10. What is the main risk of this compound component pattern?

```jsx theme={null}
<Tabs>
  <Tab />
</Tabs>
```

(with internal context)

### Options:

A. Performance issues
B. Hidden dependency on parent context
C. Cannot scale
D. JSX limitation

### ✅ Correct Answer: B

### ✔ Explanation:

Compound components rely on context → implicit coupling

👉 `<Tab>` must be inside `<Tabs>`

### ❌ Why others are wrong:

* A: Not inherently slow
* C: It scales well
* D: No JSX issue

***

# 11. What happens if context is missing?

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

(outside `<Tabs>`)

### Options:

A. Works normally
B. Uses default state
C. Likely runtime error
D. React auto-wraps

### ✅ Correct Answer: C

### ✔ Explanation:

`useContext` returns `undefined` → accessing properties causes error

### ❌ Why others are wrong:

* A: No context → broken
* B: Only if default defined
* D: React does not auto-wrap

***

# 12. What is the issue here?

```jsx theme={null}
function Card({ children }) {
  return <div>{children}</div>;
}

<Card children={<p>Hello</p>} />
```

### Options:

A. Invalid syntax
B. children prop is overridden
C. children cannot be passed explicitly
D. Nothing is wrong

### ✅ Correct Answer: D

### ✔ Explanation:

`children` is just a prop → can be passed explicitly

### ❌ Why others are wrong:

* A: Valid
* B: No override issue
* C: Allowed

***

# 13. What is the risk in this pattern?

```jsx theme={null}
function Wrapper({ children }) {
  return React.cloneElement(children, { extra: true });
}
```

### Options:

A. children cannot be cloned
B. Only works with one child
C. Breaks React rules
D. Causes memory leak

### ✅ Correct Answer: B

### ✔ Explanation:

`cloneElement` requires a **single React element**

Multiple children → error

### ❌ Why others are wrong:

* A: It can be cloned
* C: Valid API
* D: No leak

***

# 14. What is the issue with deep composition and context?

### Options:

A. Context cannot pass deeply
B. All components re-render on context change
C. Context breaks composition
D. Context cannot be nested

### ✅ Correct Answer: B

### ✔ Explanation:

Context updates → all consumers re-render

👉 Performance concern in large trees

### ❌ Why others are wrong:

* A: It can pass deeply
* C: They complement each other
* D: Nesting allowed

***

# 15. Why might this API design be problematic?

```jsx theme={null}
<Component>
  <Header />
  <Random />
</Component>
```

### Options:

A. JSX invalid
B. No control over allowed children
C. children must be array
D. React disallows mixed types

### ✅ Correct Answer: B

### ✔ Explanation:

No constraints → unpredictable structure

👉 Hard to enforce design rules

### ❌ Why others are wrong:

* A: Valid
* C: Not required
* D: Allowed

***

# 16. What happens when returning arrays from children?

```jsx theme={null}
function Wrapper({ children }) {
  return children;
}
```

### Options:

A. Error
B. Works if keys exist
C. Only first child renders
D. Array is flattened automatically

### ✅ Correct Answer: B

### ✔ Explanation:

React supports arrays, but keys are required for stability.

### ❌ Why others are wrong:

* A: No error
* C: All children render
* D: Not "flattened" automatically

***

# 🔚 Final Insight

These questions test whether you understand:

* Composition ≠ just children
* It deeply affects:

  * Reconciliation
  * Performance
  * API design
  * Debugging complexity

***

## 📘 Component Composition — Advanced Coding Problems (React)

These problems simulate **real-world UI architecture and design challenges** using component composition.

***

# 🧩 1. Flexible Layout System (Slots-Based)

### 🧠 Problem

Build a `Layout` component that supports:

* Header
* Sidebar
* Content
* Footer

Using **composition (not props drilling)**.

### ⚙️ Constraints

* Must allow optional sections
* Order should not matter
* Clean API

### ✅ Expected Usage

```jsx theme={null}
<Layout>
  <Layout.Header>Header</Layout.Header>
  <Layout.Sidebar>Sidebar</Layout.Sidebar>
  <Layout.Content>Main</Layout.Content>
</Layout>
```

***

### ⚠️ Edge Cases

* Missing sections
* Multiple headers
* Invalid children

***

### 💡 Solution (Step-by-step)

1. Use **context** to register slots
2. Identify child types via `type`
3. Render in fixed layout positions

```jsx theme={null}
const LayoutContext = React.createContext();

function Layout({ children }) {
  const slots = {};

  React.Children.forEach(children, child => {
    slots[child.type.name] = child;
  });

  return (
    <div>
      {slots.Header}
      {slots.Sidebar}
      {slots.Content}
      {slots.Footer}
    </div>
  );
}
```

***

# 🧩 2. Modal with Controlled & Uncontrolled Modes

### 🧠 Problem

Create a `Modal` that supports:

* Controlled (`isOpen`)
* Uncontrolled (`defaultOpen`)

***

### ⚙️ Constraints

* Must support both modes cleanly
* Avoid duplicate state logic

***

### ✅ Expected Behavior

* Parent can control open state
* Internal state fallback if not provided

***

### 💡 Solution

```jsx theme={null}
function Modal({ isOpen, defaultOpen, children }) {
  const [internal, setInternal] = React.useState(defaultOpen);

  const open = isOpen !== undefined ? isOpen : internal;

  return open ? <div>{children}</div> : null;
}
```

***

# 🧩 3. Accordion (Compound Components)

### 🧠 Problem

Build an accordion where items manage open/close via shared state.

***

### ⚙️ Constraints

* Only one item open at a time
* Clean composition API

***

### ✅ Expected Usage

```jsx theme={null}
<Accordion>
  <Accordion.Item title="Q1">A1</Accordion.Item>
</Accordion>
```

***

### 💡 Solution

* Use context for active index
* Each item reads & updates it

***

# 🧩 4. Tabs with Dynamic Registration

### 🧠 Problem

Tabs should:

* Auto-register children
* Support dynamic addition/removal

***

### ⚠️ Edge Cases

* Tabs added after mount
* Missing indices

***

### 💡 Solution Insight

* Use `React.Children.map`
* Use index-based tracking + keys

***

# 🧩 5. Form Builder with Composition

### 🧠 Problem

Create a `Form` component where:

* Inputs register themselves
* Form collects values

***

### ✅ Usage

```jsx theme={null}
<Form onSubmit={...}>
  <Form.Input name="email" />
  <Form.Input name="password" />
</Form>
```

***

### 💡 Solution

* Context for form state
* Inputs update shared store

***

# 🧩 6. Permission-Based Rendering Wrapper

### 🧠 Problem

Render children only if user has permission.

***

### ⚙️ Constraints

* Should support multiple permissions
* Nested composition

***

### 💡 Solution

```jsx theme={null}
function Permission({ allow, children }) {
  const user = useUser();

  return allow.includes(user.role) ? children : null;
}
```

***

# 🧩 7. Data Fetcher (Render Props vs Composition)

### 🧠 Problem

Support both:

```jsx theme={null}
<Data>{(data) => ...}</Data>
```

AND

```jsx theme={null}
<Data>
  <Child />
</Data>
```

***

### ⚠️ Edge Case

* Detect if child is function

***

### 💡 Solution

```jsx theme={null}
return typeof children === "function"
  ? children(data)
  : children;
```

***

# 🧩 8. Card with Strict Child Validation

### 🧠 Problem

Card should only allow:

* `Card.Header`
* `Card.Body`

***

### ⚠️ Edge Cases

* Invalid children
* Multiple headers

***

### 💡 Solution

```jsx theme={null}
React.Children.forEach(children, child => {
  if (![Header, Body].includes(child.type)) {
    throw new Error("Invalid child");
  }
});
```

***

# 🧩 9. List Virtualization Wrapper

### 🧠 Problem

Wrap large lists while preserving composition.

***

### ⚙️ Constraints

* Only render visible items
* Accept child renderer

***

### 💡 Solution

* Use render function
* Combine with windowing logic

***

# 🧩 10. Theme Provider with Composition

### 🧠 Problem

Provide theme to deeply nested components.

***

### 💡 Solution

```jsx theme={null}
const ThemeContext = React.createContext();

<ThemeContext.Provider value="dark">
  <Layout />
</ThemeContext.Provider>
```

***

# 🧩 11. Tooltip Wrapper (Composition Control)

### 🧠 Problem

Wrap any element with tooltip behavior.

***

### ⚠️ Edge Case

* Child must accept props

***

### 💡 Solution

```jsx theme={null}
React.cloneElement(children, {
  onMouseEnter: showTooltip
});
```

***

# 🧩 12. Error Boundary Wrapper

### 🧠 Problem

Catch errors in composed children.

***

### 💡 Solution

* Use class component
* Wrap children

***

# 🧩 13. Multi-Step Form Wizard

### 🧠 Problem

Steps defined via composition:

```jsx theme={null}
<Wizard>
  <Step />
  <Step />
</Wizard>
```

***

### 💡 Solution

* Track active step via context
* Render one step at a time

***

# 🧩 14. Portal-Based Modal System

### 🧠 Problem

Render children outside DOM hierarchy.

***

### 💡 Solution

```jsx theme={null}
ReactDOM.createPortal(children, document.body);
```

***

# 🧩 15. Drag-and-Drop Wrapper

### 🧠 Problem

Enable drag behavior for any child.

***

### ⚠️ Edge Case

* Child event conflicts

***

### 💡 Solution

* Inject handlers via cloning

***

# 🧩 16. Layout Switcher (Responsive Composition)

### 🧠 Problem

Switch layout based on screen size.

***

### 💡 Solution

* Conditional composition

```jsx theme={null}
return isMobile ? <MobileLayout /> : <DesktopLayout />;
```

***

# 🧩 17. Notification System (Stacked Composition)

### 🧠 Problem

Allow multiple notifications via composition.

***

### 💡 Solution

* Context store + dynamic children

***

# 🧩 18. Skeleton Loader Wrapper

### 🧠 Problem

Wrap content with loading placeholder.

***

### 💡 Solution

```jsx theme={null}
function Skeleton({ loading, children }) {
  return loading ? <Loader /> : children;
}
```

***

# 🧩 19. Access-Controlled Route Wrapper

### 🧠 Problem

Restrict route access via composition.

***

### 💡 Solution

```jsx theme={null}
<Route element={
  <Protected>
    <Dashboard />
  </Protected>
} />
```

***

# 🧩 20. Analytics Wrapper (Cross-Cutting Concern)

### 🧠 Problem

Track interactions across children.

***

### 💡 Solution

* Wrap children
* Inject tracking props/events

***

# 🔚 Final Takeaway

These problems test your ability to:

* Design **scalable APIs**
* Balance **flexibility vs control**
* Handle **real-world constraints**
* Understand **composition deeply (not just children)**

***

## 📘 Component Composition — Real-World Debugging Challenges (Senior Code Review)

These are **production-grade bugs** involving composition, not trivial mistakes.

***

# 🐞 1. Children Not Rendering

### ❌ Buggy Code

```jsx theme={null}
function Card({ children }) {
  return <div className="card"></div>;
}
```

### 🔍 What’s Wrong

`children` is never rendered.

### 💥 Why It Happens

In composition, children are **just props** — React won’t render them automatically.

***

### ✅ Fix

```jsx theme={null}
function Card({ children }) {
  return <div className="card">{children}</div>;
}
```

### ✅ Best Practice

Always explicitly render `children` in container components.

***

# 🐞 2. Broken Memoization Due to Inline Composition

### ❌ Buggy Code

```jsx theme={null}
const Child = React.memo(({ config }) => {
  console.log("render");
  return <div>{config.value}</div>;
});

function Parent() {
  return (
    <Child config={{ value: 1 }} />
  );
}
```

### 🔍 What’s Wrong

Child re-renders every time.

### 💥 Why It Happens

New object reference on each render → breaks `React.memo`.

***

### ✅ Fix

```jsx theme={null}
function Parent() {
  const config = React.useMemo(() => ({ value: 1 }), []);
  return <Child config={config} />;
}
```

### ✅ Best Practice

Stabilize props in composed trees using `useMemo`.

***

# 🐞 3. State Leakage Due to Missing Keys

### ❌ Buggy Code

```jsx theme={null}
{items.map((item, index) => (
  <Input key={index} value={item.value} />
))}
```

### 🔍 What’s Wrong

Inputs show incorrect values after reordering.

### 💥 Why It Happens

Index-based keys → React reuses wrong components.

***

### ✅ Fix

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

### ✅ Best Practice

Never use index as key in dynamic composed lists.

***

# 🐞 4. Render Prop Misuse

### ❌ Buggy Code

```jsx theme={null}
function Fetcher({ children }) {
  const data = { name: "John" };
  return <div>{children}</div>;
}
```

Usage:

```jsx theme={null}
<Fetcher>
  {(data) => <p>{data.name}</p>}
</Fetcher>
```

### 🔍 What’s Wrong

Function never executes.

### 💥 Why It Happens

React does not auto-call function children.

***

### ✅ Fix

```jsx theme={null}
return <div>{children(data)}</div>;
```

### ✅ Best Practice

Detect and handle function-as-children explicitly.

***

# 🐞 5. CloneElement Crash with Multiple Children

### ❌ Buggy Code

```jsx theme={null}
function Wrapper({ children }) {
  return React.cloneElement(children, { active: true });
}
```

Usage:

```jsx theme={null}
<Wrapper>
  <Button />
  <Button />
</Wrapper>
```

### 🔍 What’s Wrong

Runtime error.

### 💥 Why It Happens

`cloneElement` expects **single React element**, not array.

***

### ✅ Fix

```jsx theme={null}
return React.Children.map(children, child =>
  React.cloneElement(child, { active: true })
);
```

### ✅ Best Practice

Always handle multiple children via `React.Children.map`.

***

# 🐞 6. Context Undefined in Compound Component

### ❌ Buggy Code

```jsx theme={null}
const TabsContext = React.createContext();

function Tab() {
  const { active } = React.useContext(TabsContext);
  return <div>{active}</div>;
}
```

Usage:

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

### 🔍 What’s Wrong

App crashes.

### 💥 Why It Happens

No provider → `useContext` returns `undefined`.

***

### ✅ Fix

```jsx theme={null}
const context = React.useContext(TabsContext);
if (!context) throw new Error("Tab must be inside Tabs");
```

### ✅ Best Practice

Guard compound components against missing providers.

***

# 🐞 7. Hidden Re-render Cascade

### ❌ Buggy Code

```jsx theme={null}
function Parent() {
  const [count, setCount] = useState(0);

  return (
    <Wrapper>
      <Child />
    </Wrapper>
  );
}
```

### 🔍 What’s Wrong

Child re-renders even if it doesn't use `count`.

### 💥 Why It Happens

Parent re-render → all children re-render.

***

### ✅ Fix

```jsx theme={null}
const Child = React.memo(() => { ... });
```

### ✅ Best Practice

Memoize deeply composed children.

***

# 🐞 8. Incorrect Child Type Assumption

### ❌ Buggy Code

```jsx theme={null}
React.Children.forEach(children, child => {
  console.log(child.props.name);
});
```

### 🔍 What’s Wrong

Crashes when child is string/null.

### 💥 Why It Happens

Children can be:

* strings
* null
* arrays

***

### ✅ Fix

```jsx theme={null}
if (React.isValidElement(child)) {
  console.log(child.props.name);
}
```

### ✅ Best Practice

Always validate children before accessing props.

***

# 🐞 9. Function Child Not Called Conditionally

### ❌ Buggy Code

```jsx theme={null}
return children && children(data);
```

### 🔍 What’s Wrong

Crashes if children is not function.

***

### 💥 Why It Happens

Assumes children is callable.

***

### ✅ Fix

```jsx theme={null}
return typeof children === "function"
  ? children(data)
  : children;
```

### ✅ Best Practice

Support both patterns safely.

***

# 🐞 10. Overwriting Event Handlers

### ❌ Buggy Code

```jsx theme={null}
React.cloneElement(children, {
  onClick: () => console.log("wrapper")
});
```

### 🔍 What’s Wrong

Child’s original `onClick` lost.

***

### 💥 Why It Happens

Props are overwritten.

***

### ✅ Fix

```jsx theme={null}
const original = children.props.onClick;

React.cloneElement(children, {
  onClick: (e) => {
    original?.(e);
    console.log("wrapper");
  }
});
```

### ✅ Best Practice

Merge, don’t override props.

***

# 🐞 11. Multiple Slot Collision

### ❌ Buggy Code

```jsx theme={null}
slots[child.type.name] = child;
```

### 🔍 What’s Wrong

Only last child kept.

***

### 💥 Why It Happens

Same key overwritten.

***

### ✅ Fix

```jsx theme={null}
slots[child.type.name] = [
  ...(slots[child.type.name] || []),
  child
];
```

### ✅ Best Practice

Handle multiple instances safely.

***

# 🐞 12. Stale Closure in Composed Callback

### ❌ Buggy Code

```jsx theme={null}
function Wrapper({ children }) {
  const [count, setCount] = useState(0);

  return React.cloneElement(children, {
    onClick: () => setCount(count + 1)
  });
}
```

### 🔍 What’s Wrong

May use stale `count`.

***

### 💥 Why It Happens

Closure captures old state.

***

### ✅ Fix

```jsx theme={null}
onClick: () => setCount(c => c + 1)
```

### ✅ Best Practice

Use functional updates in composed callbacks.

***

# 🐞 13. Fragment Children Misinterpretation

### ❌ Buggy Code

```jsx theme={null}
React.Children.count(children) === 1
```

### 🔍 What’s Wrong

Fails for fragments.

***

### 💥 Why It Happens

Fragments wrap multiple children but count as one.

***

### ✅ Fix

```jsx theme={null}
React.Children.toArray(children).length
```

### ✅ Best Practice

Normalize children before inspection.

***

# 🐞 14. Conditional Rendering Losing State

### ❌ Buggy Code

```jsx theme={null}
{show && <Child />}
```

### 🔍 What’s Wrong

Child state resets when toggled.

***

### 💥 Why It Happens

Component unmounts/remounts.

***

### ✅ Fix

```jsx theme={null}
<Child hidden={!show} />
```

### ✅ Best Practice

Avoid unmounting when state must persist.

***

# 🐞 15. Deep Composition Causing Prop Drilling

### ❌ Buggy Code

```jsx theme={null}
<A data={data}>
  <B data={data}>
    <C data={data} />
  </B>
</A>
```

### 🔍 What’s Wrong

Unnecessary prop passing.

***

### 💥 Why It Happens

Poor composition design.

***

### ✅ Fix

Use context:

```jsx theme={null}
<DataContext.Provider value={data}>
  <C />
</DataContext.Provider>
```

### ✅ Best Practice

Use context for deeply shared data.

***

# 🐞 16. Unstable Child Identity

### ❌ Buggy Code

```jsx theme={null}
<Wrapper>
  {() => <Child />}
</Wrapper>
```

### 🔍 What’s Wrong

New function every render → re-renders.

***

### 💥 Why It Happens

Function identity changes.

***

### ✅ Fix

```jsx theme={null}
const renderChild = useCallback(() => <Child />, []);
```

### ✅ Best Practice

Stabilize function props.

***

# 🐞 17. Unexpected Rendering Order

### ❌ Buggy Code

```jsx theme={null}
React.Children.map(children, child => {
  return condition ? child : null;
});
```

### 🔍 What’s Wrong

Keys shift → order instability.

***

### 💥 Why It Happens

Filtering without preserving keys.

***

### ✅ Fix

```jsx theme={null}
React.Children.toArray(children).filter(...)
```

### ✅ Best Practice

Normalize + filter safely.

***

# 🐞 18. Infinite Re-render Loop via Composition

### ❌ Buggy Code

```jsx theme={null}
function Parent() {
  const [state, setState] = useState(0);

  return (
    <Child update={() => setState(state + 1)} />
  );
}
```

### 🔍 What’s Wrong

Child triggers update → infinite loop.

***

### 💥 Why It Happens

Unstable callback causes repeated updates.

***

### ✅ Fix

```jsx theme={null}
const update = useCallback(() => {
  setState(s => s + 1);
}, []);
```

### ✅ Best Practice

Stabilize callbacks passed through composition.

***

# 🔚 Final Takeaway

Real-world composition bugs usually come from:

* ❌ Wrong assumptions about `children`
* ❌ Unstable references (objects/functions)
* ❌ Hidden coupling (context, compound patterns)
* ❌ Misuse of React utilities (`cloneElement`, `Children`)
* ❌ Reconciliation misunderstandings

***

## 📘 Component Composition — Real-World Machine Coding Problems (Senior Architect Level)

These problems simulate **production-grade frontend architecture challenges** where **component composition is central**.

***

# 🧩 1. Headless Dropdown System (Composable API)

### 🧠 Problem

Build a fully accessible dropdown system with:

* Trigger
* Menu
* Items

### ✅ Requirements

* Keyboard navigation (↑ ↓ Enter Esc)
* Controlled + uncontrolled modes
* Custom rendering of items

***

### 🎯 UI Behavior

* Clicking trigger toggles menu
* Arrow keys navigate items
* Only one item active

***

### 🔄 State/Data Flow

* Shared via context:

  * `isOpen`
  * `activeIndex`
  * `selectItem`

***

### ⚠️ Edge Cases

* Click outside to close
* Dynamic items list
* Nested dropdowns

***

### ⚡ Performance

* Avoid re-renders on hover
* Memoize item list

***

### 🏗 Suggested Architecture

```jsx id="d1" theme={null}
<Dropdown>
  <Dropdown.Trigger />
  <Dropdown.Menu>
    <Dropdown.Item />
  </Dropdown.Menu>
</Dropdown>
```

***

### 🛠 Approach

1. Create context
2. Register items dynamically
3. Handle keyboard events globally
4. Use refs for focus control

***

# 🧩 2. Headless Modal System with Portal

### 🧠 Problem

Create a composable modal system supporting:

* Multiple modals
* Nested modals
* Portal rendering

***

### 🎯 UI Behavior

* Modal overlays page
* Focus trapped inside
* Escape closes modal

***

### 🔄 Data Flow

* Global modal manager (context/store)

***

### ⚠️ Edge Cases

* Multiple modals stacked
* Background scroll lock

***

### ⚡ Performance

* Avoid re-rendering entire app
* Use portals for isolation

***

### 🏗 Architecture

```jsx id="d2" theme={null}
<Modal>
  <Modal.Trigger />
  <Modal.Content />
</Modal>
```

***

### 🛠 Approach

1. Use `createPortal`
2. Manage modal stack
3. Trap focus with refs

***

# 🧩 3. Dynamic Form Builder (Schema + Composition)

### 🧠 Problem

Build a form system where:

* Fields self-register
* Supports validation & dynamic fields

***

### 🎯 UI Behavior

* Real-time validation
* Dynamic addition/removal of fields

***

### 🔄 Data Flow

* Central form state via context

***

### ⚠️ Edge Cases

* Nested fields
* Async validation

***

### ⚡ Performance

* Avoid re-rendering entire form
* Field-level subscriptions

***

### 🏗 Architecture

```jsx id="d3" theme={null}
<Form>
  <Form.Field name="email" />
</Form>
```

***

### 🛠 Approach

1. Create field registry
2. Use context for state
3. Isolate updates per field

***

# 🧩 4. Compound Tabs with Lazy Rendering

### 🧠 Problem

Tabs where inactive panels are not rendered.

***

### ⚠️ Edge Cases

* Preserving state on unmount
* Dynamic tab addition

***

### ⚡ Performance

* Lazy mount panels
* Memoize tab content

***

### 🏗 Architecture

```jsx id="d4" theme={null}
<Tabs>
  <Tabs.List />
  <Tabs.Panel />
</Tabs>
```

***

### 🛠 Approach

* Track active tab
* Conditionally render panel

***

# 🧩 5. Notification System (Global + Composable)

### 🧠 Problem

Create a toast system with:

* Stacked notifications
* Auto-dismiss
* Custom content

***

### 🔄 Data Flow

* Global context store

***

### ⚠️ Edge Cases

* Rapid fire notifications
* Duplicate messages

***

### ⚡ Performance

* Avoid re-rendering all toasts

***

### 🏗 Architecture

```jsx id="d5" theme={null}
<ToastProvider>
  <App />
</ToastProvider>
```

***

### 🛠 Approach

* Maintain queue
* Render via portal

***

# 🧩 6. Drag-and-Drop Composable System

### 🧠 Problem

Enable drag-drop via composition.

***

### ⚠️ Edge Cases

* Nested draggables
* Performance on large lists

***

### ⚡ Performance

* Avoid full re-renders during drag

***

### 🏗 Architecture

```jsx id="d6" theme={null}
<Draggable>
  <Item />
</Draggable>
```

***

### 🛠 Approach

* Inject props via cloneElement
* Use refs for DOM tracking

***

# 🧩 7. Virtualized List with Render Composition

### 🧠 Problem

Render large datasets efficiently.

***

### ⚠️ Edge Cases

* Dynamic item heights
* Scroll jumps

***

### ⚡ Performance

* Windowing
* Memoized item renderer

***

### 🏗 Architecture

```jsx id="d7" theme={null}
<VirtualList>
  {(item) => <Row item={item} />}
</VirtualList>
```

***

### 🛠 Approach

* Calculate visible range
* Render subset

***

# 🧩 8. Multi-Step Wizard

### 🧠 Problem

Composable steps with shared state.

***

### ⚠️ Edge Cases

* Skippable steps
* Async validation

***

### 🏗 Architecture

```jsx id="d8" theme={null}
<Wizard>
  <Step />
</Wizard>
```

***

### 🛠 Approach

* Track current step
* Share state via context

***

# 🧩 9. Access-Control Wrapper System

### 🧠 Problem

Control UI visibility based on roles.

***

### ⚠️ Edge Cases

* Nested permissions
* Async auth

***

### 🏗 Architecture

```jsx id="d9" theme={null}
<Protected roles={["admin"]}>
  <Dashboard />
</Protected>
```

***

### 🛠 Approach

* Context-based auth
* Conditional rendering

***

# 🧩 10. Analytics Wrapper

### 🧠 Problem

Track user interactions across app.

***

### ⚠️ Edge Cases

* Prevent duplicate tracking
* Debounce events

***

### 🏗 Architecture

```jsx id="d10" theme={null}
<Track event="click">
  <Button />
</Track>
```

***

### 🛠 Approach

* Inject handlers via cloning
* Central tracking system

***

# 🧩 11. Layout System with Responsive Composition

### 🧠 Problem

Switch layout dynamically.

***

### ⚠️ Edge Cases

* Resize events
* SSR mismatch

***

### 🏗 Architecture

```jsx id="d11" theme={null}
<ResponsiveLayout />
```

***

### 🛠 Approach

* Media queries + composition switching

***

# 🧩 12. Skeleton Loader Wrapper

### 🧠 Problem

Wrap any component with loading state.

***

### ⚠️ Edge Cases

* Partial loading
* Layout shifts

***

### 🛠 Approach

* Conditional rendering + placeholder

***

# 🧩 13. Infinite Scroll Feed

### 🧠 Problem

Composable feed with lazy loading.

***

### ⚠️ Edge Cases

* Scroll threshold issues
* Duplicate fetches

***

### 🛠 Approach

* IntersectionObserver
* State batching

***

# 🧩 14. Global Search Overlay

### 🧠 Problem

Search UI accessible anywhere.

***

### ⚠️ Edge Cases

* Keyboard shortcut conflicts
* Debounce search

***

### 🛠 Approach

* Portal + context

***

# 🧩 15. Table System (Headless + Composable)

### 🧠 Problem

Customizable table:

* Columns
* Sorting
* Pagination

***

### ⚠️ Edge Cases

* Large datasets
* Column reordering

***

### 🛠 Approach

* Headless logic + UI composition

***

# 🧩 16. Feature Flag Wrapper

### 🧠 Problem

Enable/disable features dynamically.

***

### ⚠️ Edge Cases

* Async flags
* A/B testing

***

### 🛠 Approach

* Context-based flags

***

# 🧩 17. Error Boundary System (Composable)

### 🧠 Problem

Wrap parts of app for error isolation.

***

### ⚠️ Edge Cases

* Nested boundaries
* Reset behavior

***

### 🛠 Approach

* Class-based error boundaries

***

# 🧩 18. Command Palette (Keyboard Driven UI)

### 🧠 Problem

Global command system (like VS Code).

***

### ⚠️ Edge Cases

* Focus management
* Search ranking

***

### 🛠 Approach

* Context + portal + keyboard events

***

# 🧩 19. Timeline/Activity Feed System

### 🧠 Problem

Composable event feed with grouping.

***

### ⚠️ Edge Cases

* Time grouping
* Dynamic updates

***

### 🛠 Approach

* Data transformation + composed UI

***

# 🧩 20. Nested Menu System

### 🧠 Problem

Multi-level navigation menus.

***

### ⚠️ Edge Cases

* Keyboard navigation
* Deep nesting

***

### 🛠 Approach

* Recursive composition
* Context for active state

***

# 🔚 Final Takeaway

These problems test **true senior-level skills**:

* Designing **composable APIs**
* Managing **state across trees**
* Handling **performance + edge cases**
* Balancing **flexibility vs control**

***

## 📘 FAANG-Level Interview Questions — Component Composition (React)

These questions probe **architecture thinking, trade-offs, debugging ability, and performance awareness** — not surface knowledge.

***

# 1. Design a flexible `Modal` API using composition. What trade-offs would you consider?

### 🔍 Follow-ups

* How would you support nested modals?
* How would you prevent misuse of subcomponents?

### ✅ Strong Answer

* Use compound components:

```jsx theme={null}
<Modal>
  <Modal.Trigger />
  <Modal.Content />
</Modal>
```

* Share state via context
* Use portal for rendering
* Add guards for invalid usage

### 💡 Trade-offs

* Flexibility vs API constraints
* Context coupling vs explicit props

### ❌ Weak Answer

“Just pass `isOpen` prop and render children”

👉 Fails because:

* Ignores composability
* Doesn’t scale for complex UI

***

# 2. When would you prefer render props over composition?

### 🔍 Follow-ups

* What are performance implications?
* How does it affect readability?

### ✅ Strong Answer

* Use render props when:

  * UI depends on dynamic data/logic
  * Need runtime control

```jsx theme={null}
<Data>{(data) => <UI data={data} />}</Data>
```

### 💡 Trade-off

* More flexible but harder to read/debug

### ❌ Weak Answer

“Render props are just another way to pass children”

👉 Misses key difference: **function execution vs static structure**

***

# 3. How does React treat `children` internally, and why does it matter for performance?

### 🔍 Follow-ups

* How does reconciliation use keys?
* What happens with unstable children?

### ✅ Strong Answer

* `children` → part of `props`
* Converted into fiber nodes
* Reconciliation depends on:

  * Keys
  * Order

👉 Unstable children → unnecessary re-renders

### ❌ Weak Answer

“Children is just JSX”

👉 Too shallow, no understanding of reconciliation

***

# 4. You see unnecessary re-renders in a deeply composed tree. How do you debug?

### 🔍 Follow-ups

* What tools would you use?
* How do you isolate the issue?

### ✅ Strong Answer

1. Use React DevTools (highlight updates)
2. Check prop identity (objects/functions)
3. Add `React.memo`
4. Profile renders

### ❌ Weak Answer

“Use memo everywhere”

👉 Blind optimization without root cause analysis

***

# 5. Design a `Tabs` system using composition. How do you handle state sharing?

### 🔍 Follow-ups

* What if tabs are dynamically added?
* How do you prevent misuse?

### ✅ Strong Answer

* Compound components + context
* Track active index
* Register children dynamically

### ❌ Weak Answer

“Pass active tab as prop to each Tab”

👉 Leads to prop drilling and poor scalability

***

# 6. What are the risks of overusing composition?

### 🔍 Follow-ups

* When does composition hurt readability?
* How do you balance abstraction?

### ✅ Strong Answer

* Deep nesting → hard debugging
* Implicit structure → unclear APIs
* Hidden coupling via context

### ❌ Weak Answer

“No downsides, composition is always good”

👉 Shows lack of real-world experience

***

# 7. How do you enforce constraints in a composable API?

### 🔍 Follow-ups

* Compile-time vs runtime validation?

### ✅ Strong Answer

* Use:

  * TypeScript typings
  * Runtime validation (`child.type`)
  * Controlled compound components

### ❌ Weak Answer

“Document it”

👉 Documentation is not enforcement

***

# 8. Compare composition vs custom hooks for reuse.

### 🔍 Follow-ups

* Can they be combined?

### ✅ Strong Answer

* Composition → UI reuse
* Hooks → logic reuse

👉 Best systems combine both

### ❌ Weak Answer

“They are interchangeable”

👉 Incorrect mental model

***

# 9. How does composition impact bundle size and performance?

### 🔍 Follow-ups

* Tree-shaking implications?

### ✅ Strong Answer

* More components ≠ worse performance
* But:

  * More layers → more renders
  * Inline functions/objects hurt memoization

### ❌ Weak Answer

“More components always slower”

👉 Oversimplified and incorrect

***

# 10. How would you design a headless UI component system?

### 🔍 Follow-ups

* How do you separate logic from UI?

### ✅ Strong Answer

* Provide logic via hooks/context
* Let consumers compose UI

```jsx theme={null}
<Dropdown>
  <Dropdown.Trigger />
  <Dropdown.Menu />
</Dropdown>
```

### ❌ Weak Answer

“Just style components”

👉 Misses headless concept

***

# 11. What issues arise with `React.cloneElement` in composition?

### 🔍 Follow-ups

* Alternatives?

### ✅ Strong Answer

* Only works with single child
* Overrides props unintentionally
* Breaks ref forwarding

### ❌ Weak Answer

“It’s fine to use everywhere”

👉 Ignores limitations

***

# 12. How do keys affect composed components beyond lists?

### 🔍 Follow-ups

* Can keys reset state?

### ✅ Strong Answer

* Keys control identity
* Changing key → remount → state reset

### ❌ Weak Answer

“Keys are only for lists”

👉 Incorrect

***

# 13. Design a system to avoid prop drilling in deep composition.

### 🔍 Follow-ups

* When NOT to use context?

### ✅ Strong Answer

* Use context for shared data
* Avoid overusing context (performance issues)

### ❌ Weak Answer

“Always use context”

👉 Ignores trade-offs

***

# 14. What is a subtle bug when using function-as-children?

### 🔍 Follow-ups

* Performance implications?

### ✅ Strong Answer

* Function recreated each render
* Causes re-renders if not memoized

### ❌ Weak Answer

“No issues”

👉 Misses real-world impact

***

# 15. How do you design a scalable layout system using composition?

### 🔍 Follow-ups

* Slot-based vs children-based?

### ✅ Strong Answer

* Use slots for clarity:

```jsx theme={null}
<Layout header={} sidebar={} />
```

OR compound pattern

### ❌ Weak Answer

“Just use divs”

👉 Not architectural thinking

***

# 16. How would you debug a broken compound component system?

### 🔍 Follow-ups

* What if context is undefined?

### ✅ Strong Answer

* Check provider presence
* Validate usage
* Add error boundaries

### ❌ Weak Answer

“Check console logs”

👉 Too shallow

***

# 17. When does composition break encapsulation?

### 🔍 Follow-ups

* How do you fix it?

### ✅ Strong Answer

* Exposing internal state setters
* Allowing uncontrolled manipulation

👉 Fix via controlled APIs

### ❌ Weak Answer

“It doesn’t”

👉 Incorrect

***

# 18. How does composition interact with Suspense and lazy loading?

### 🔍 Follow-ups

* Where do you place boundaries?

### ✅ Strong Answer

* Wrap composed parts with Suspense
* Lazy load heavy children

### ❌ Weak Answer

“Suspense handles everything”

👉 Oversimplified

***

# 19. Design a reusable analytics wrapper using composition.

### 🔍 Follow-ups

* Avoid double tracking?

### ✅ Strong Answer

* Wrap children
* Inject event handlers carefully
* Deduplicate events

### ❌ Weak Answer

“Log inside component”

👉 Not reusable/composable

***

# 20. What is the hardest part of designing composable systems at scale?

### 🔍 Follow-ups

* How do you measure success?

### ✅ Strong Answer

* Balancing:

  * Flexibility
  * Constraints
  * Performance
* Avoiding hidden coupling

### ❌ Weak Answer

“Just reuse components”

👉 Misses system design depth

***

# 🔚 Final Insight

A strong candidate demonstrates:

* Deep understanding of **React internals**
* Ability to reason about **trade-offs**
* Awareness of **performance & debugging**
* Skill in designing **clean, scalable APIs**

***
