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

# Compound components

# 📘 Compound Components in React — Complete Theory Guide

***

## 1. 📌 Introduction

### 🔹 What are Compound Components?

**Compound Components** is a design pattern in React where:

* Multiple components work together as a **single cohesive unit**
* Parent component manages shared state
* Child components **implicitly communicate via context or props**

👉 In simple terms:

> Compound components = a group of components that share logic and state internally but expose a flexible API externally

***

### 🔹 Example (Mental Model)

```js id="cmp1" theme={null}
<Tabs>
  <Tabs.List>
    <Tabs.Tab>Tab 1</Tabs.Tab>
    <Tabs.Tab>Tab 2</Tabs.Tab>
  </Tabs.List>

  <Tabs.Panel>Content 1</Tabs.Panel>
  <Tabs.Panel>Content 2</Tabs.Panel>
</Tabs>
```

👉 All components (`Tabs.Tab`, `Tabs.Panel`) work together via shared state.

***

### 🔹 Why is it Important?

Without compound components:

* You pass a lot of props manually (prop drilling)
* UI becomes tightly coupled

With compound components:

* Clean and expressive API
* Implicit communication between components
* High flexibility in layout

***

### 🔹 When and Why Do We Use It?

Use compound components when:

* 🧩 Multiple components need to share state
* 🎨 UI structure should be flexible
* 🔄 You want reusable UI patterns (tabs, dropdowns, accordions)
* 🧠 You want **declarative APIs**

***

### 🔹 Real-World Use Cases

* Tabs
* Accordion
* Dropdown/Menu
* Modal systems
* Form groups

***

## 2. ⚙️ Concepts / Internal Workings

***

### 🔹 1. Parent Controls State

The parent component:

* Holds shared state
* Provides it to children

```js id="cmp2" theme={null}
const [activeIndex, setActiveIndex] = useState(0);
```

***

### 🔹 2. Children Access State

Children consume state via:

* Context (most common)
* Props (less flexible)

***

### 🔹 3. Context as Backbone

Compound components usually rely on **React Context**

```js id="cmp3" theme={null}
const TabsContext = createContext();
```

👉 Why?

* Avoid prop drilling
* Allow deep nesting

***

### 🔹 4. Implicit Communication

Child components don’t receive explicit props like:

```js id="cmp4" theme={null}
// ❌ Not needed
<Tab isActive={true} />
```

Instead:

* They derive state from context

***

### 🔹 5. Component Composition

Compound components leverage:

> Composition over configuration

Instead of:

```js id="cmp5" theme={null}
<Tabs tabs={[...]} />
```

You write:

```js id="cmp6" theme={null}
<Tabs>
  <Tabs.Tab />
</Tabs>
```

***

### 🔹 6. Relationship with Other Patterns

| Pattern             | Relationship     |
| ------------------- | ---------------- |
| HOC                 | Structural reuse |
| Render Props        | Logic sharing    |
| Hooks               | Internal logic   |
| Compound Components | UI composition   |

👉 Compound components = **UI-level abstraction**

***

## 3. 🧪 Syntax & Examples

***

## 🔹 Example 1: Tabs (Core Example)

### Step 1: Create Context

```js id="cmp7" theme={null}
const TabsContext = React.createContext();
```

***

### Step 2: Parent Component

```js id="cmp8" theme={null}
function Tabs({ children }) {
  const [activeIndex, setActiveIndex] = useState(0);

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

***

### Step 3: Tab Component

```js id="cmp9" theme={null}
function Tab({ index, children }) {
  const { activeIndex, setActiveIndex } = useContext(TabsContext);

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

***

### Step 4: Panel Component

```js id="cmp10" theme={null}
function Panel({ index, children }) {
  const { activeIndex } = useContext(TabsContext);

  return activeIndex === index ? <div>{children}</div> : null;
}
```

***

### Step 5: Attach Subcomponents

```js id="cmp11" theme={null}
Tabs.Tab = Tab;
Tabs.Panel = Panel;
```

***

### Usage:

```js id="cmp12" theme={null}
<Tabs>
  <Tabs.Tab index={0}>Tab 1</Tabs.Tab>
  <Tabs.Tab index={1}>Tab 2</Tabs.Tab>

  <Tabs.Panel index={0}>Content 1</Tabs.Panel>
  <Tabs.Panel index={1}>Content 2</Tabs.Panel>
</Tabs>
```

***

## 🔹 Example 2: Accordion

```js id="cmp13" theme={null}
function Accordion({ children }) {
  const [openIndex, setOpenIndex] = useState(null);

  return (
    <AccordionContext.Provider value={{ openIndex, setOpenIndex }}>
      {children}
    </AccordionContext.Provider>
  );
}
```

***

## 🔹 Example 3: Dropdown

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

***

## 🔹 Variation: Without Context (Less Flexible)

```js id="cmp15" theme={null}
React.Children.map(children, child =>
  React.cloneElement(child, { activeIndex })
);
```

👉 Works, but:

* Harder to scale
* Limited nesting

***

## 4. ⚠️ Edge Cases / Common Mistakes

***

### 🔹 1. Using Component Outside Parent

```js id="cmp16" theme={null}
<Tabs.Tab /> // ❌ outside Tabs
```

### Problem:

* `useContext` returns undefined

### ✅ Fix:

```js id="cmp17" theme={null}
if (!context) throw new Error("Must be used within Tabs");
```

***

### 🔹 2. Overusing Context (Performance Issues)

* Every context update → re-renders all consumers

### ✅ Fix:

* Split contexts
* Memoize values

***

### 🔹 3. Index-Based Logic Bugs

```js id="cmp18" theme={null}
index={0}
```

👉 Reordering components breaks logic

### ✅ Fix:

* Use stable IDs

***

### 🔹 4. Implicit Coupling

* Children depend on parent context
* Hard to reuse independently

***

### 🔹 5. Too Much Magic

* Hidden state flow can confuse developers

***

### 🔹 6. Incorrect Nesting

```js id="cmp19" theme={null}
<Tabs.Panel />
<Tabs.Tab />
```

👉 Order mismatch → incorrect UI

***

### 🔹 7. Uncontrolled vs Controlled State

👉 Sometimes you need both:

```js id="cmp20" theme={null}
<Tabs activeIndex={1} />
```

***

## 5. ✅ Best Practices

***

### 🔹 1. Use Context for Shared State

✔ Avoid prop drilling
✔ Enable flexible composition

***

### 🔹 2. Validate Usage

```js id="cmp21" theme={null}
if (!context) {
  throw new Error("Component must be inside provider");
}
```

***

### 🔹 3. Keep API Declarative

✔ Prefer:

```js id="cmp22" theme={null}
<Tabs>
  <Tabs.Tab />
</Tabs>
```

❌ Avoid:

```js id="cmp23" theme={null}
<Tabs tabs={[]} />
```

***

### 🔹 4. Support Controlled + Uncontrolled

```js id="cmp24" theme={null}
const isControlled = activeIndex !== undefined;
```

***

### 🔹 5. Memoize Context Value

```js id="cmp25" theme={null}
const value = useMemo(() => ({ activeIndex }), [activeIndex]);
```

***

### 🔹 6. Split Contexts for Performance

* One for state
* One for actions

***

### 🔹 7. Use Clear Naming

```js id="cmp26" theme={null}
Tabs.List
Tabs.Item
Tabs.Panel
```

***

### 🔹 8. Avoid Index-Based Keys

✔ Use unique IDs

***

### 🔹 9. Provide Defaults

* Avoid crashes when props missing

***

### 🔹 10. Document Component Contracts

Explain:

* Required structure
* Expected usage

***

# 🧠 Final Mental Model

* Compound components = **collaborative components**
* Parent manages state
* Children consume state implicitly
* Focus on **composition and flexibility**

***

## 🔚 Key Insight

Compound components represent:

> The shift from “configuration-driven UI” → “composition-driven UI”

***

👉 They are widely used in:

* UI libraries (e.g., Radix UI, Headless UI)
* Design systems

***

# 🧠 Senior-Level Conceptual Questions — Compound Components (Deep Dive)

***

## 1. What problem do compound components solve that props-based APIs struggle with?

### ✅ Answer

Compound components solve **rigidity and prop explosion** in complex UI components.

### 🔴 Problem with props-based APIs:

```js theme={null}
<Tabs tabs={[...]} activeIndex={0} onChange={...} />
```

* Hard to customize UI structure
* Limited flexibility
* Requires large configuration objects

### 🟢 Compound Components Solution:

```js theme={null}
<Tabs>
  <Tabs.Tab>Tab 1</Tabs.Tab>
  <Tabs.Panel>Content</Tabs.Panel>
</Tabs>
```

### 💡 Why:

* Moves from **configuration → composition**
* Gives full control over layout

### 🔁 Comparison:

| Approach            | Limitation |
| ------------------- | ---------- |
| Props-based         | Rigid      |
| Compound Components | Flexible   |

***

## 2. How do compound components work internally in React?

### ✅ Answer

They rely on:

1. **Shared state (parent)**
2. **Context API**
3. **Implicit communication**

```js theme={null}
const Context = createContext();

function Parent({ children }) {
  const state = useState();
  return <Context.Provider value={state}>{children}</Context.Provider>;
}
```

Children:

```js theme={null}
const { value } = useContext(Context);
```

### 💡 Why:

* Context removes need for prop drilling
* Enables deep nesting

***

## 3. Why is Context essential for scalable compound components?

### ✅ Answer

Without context:

* You must pass props manually → brittle and verbose

With context:

* Any child can access shared state regardless of depth

### 🔴 Alternative:

```js theme={null}
React.cloneElement(child, { value });
```

### ❌ Problems:

* Only works for direct children
* Breaks with nesting

### 💡 Conclusion:

Context enables **true composition flexibility**

***

## 4. What are the main performance concerns with compound components?

### ✅ Answer

### 🔴 Problem:

* Context updates → re-render all consumers

### 💡 Why:

React re-renders all components using that context

### 🟢 Solutions:

* Split context (state vs actions)
* Memoize values

```js theme={null}
const value = useMemo(() => ({ active }), [active]);
```

***

## 5. How do compound components enable inversion of control?

### ✅ Answer

Parent:

* Manages logic

Consumer:

* Controls structure and layout

```js theme={null}
<Tabs>
  <CustomHeader />
  <Tabs.Panel />
</Tabs>
```

### 💡 Why:

* Consumer decides UI
* Parent only provides behavior

***

## 6. What are the trade-offs between compound components and render props?

### ✅ Answer

| Aspect      | Compound Components | Render Props   |
| ----------- | ------------------- | -------------- |
| Readability | Higher              | Lower (nested) |
| Flexibility | High                | Very high      |
| Performance | Better              | Can degrade    |
| API style   | Declarative         | Functional     |

### 💡 Insight:

* Compound components = better UX for UI composition
* Render props = more dynamic but verbose

***

## 7. What are the trade-offs between compound components and hooks?

### ✅ Answer

| Aspect      | Compound Components | Hooks    |
| ----------- | ------------------- | -------- |
| UI control  | High                | None     |
| Logic reuse | Limited             | Strong   |
| Structure   | Explicit            | Flexible |

### 💡 Insight:

* Hooks handle logic
* Compound components handle UI structure

👉 Often used together

***

## 8. Why can compound components break when used outside their parent?

### ✅ Answer

```js theme={null}
<Tabs.Tab /> // ❌
```

### 🔴 Problem:

* No context provider → `undefined`

### 💡 Why:

Context is required for communication

### 🟢 Fix:

```js theme={null}
if (!context) throw new Error("Must be inside Tabs");
```

***

## 9. What are subtle bugs caused by index-based coordination?

### ✅ Answer

```js theme={null}
<Tabs.Tab index={0} />
```

### 🔴 Problem:

* Reordering breaks mapping

### 💡 Why:

Index is not stable

### 🟢 Fix:

* Use unique IDs

***

## 10. How would you design a controlled vs uncontrolled compound component?

### ✅ Answer

```js theme={null}
function Tabs({ activeIndex: controlledIndex }) {
  const [internalIndex, setInternalIndex] = useState(0);

  const isControlled = controlledIndex !== undefined;
  const activeIndex = isControlled ? controlledIndex : internalIndex;
}
```

### 💡 Why:

* Allows external control
* Improves flexibility

***

## 11. Why can compound components lead to implicit coupling?

### ✅ Answer

* Child components depend on context structure
* Cannot function independently

### 💡 Why:

Hidden dependency on parent

### Trade-off:

* Flexibility vs independence

***

## 12. How do you debug compound component issues in production?

### ✅ Answer

Steps:

1. Check context provider presence
2. Inspect context values
3. Verify component hierarchy
4. Add runtime validations

### 💡 Why:

Most bugs come from incorrect structure

***

## 13. How would you design a scalable compound component API?

### ✅ Answer

Principles:

* Clear naming (`Tabs.List`, `Tabs.Panel`)
* Minimal required props
* Context-based communication

```js theme={null}
<Tabs>
  <Tabs.List />
  <Tabs.Panel />
</Tabs>
```

***

## 14. What happens when context value changes frequently?

### ✅ Answer

* All consumers re-render

### 💡 Why:

Context triggers updates globally

### 🟢 Fix:

* Split contexts
* Memoize values

***

## 15. When should you avoid compound components?

### ✅ Answer

Avoid when:

* Simple UI
* No shared state
* Performance critical

👉 Prefer simple props or hooks

***

## 16. What is the biggest architectural advantage of compound components?

### ✅ Answer

👉 **Declarative and flexible UI composition**

* Developers control layout
* Logic remains centralized

***

## 17. How do compound components handle deeply nested children?

### ✅ Answer

Thanks to context:

```js theme={null}
<Tabs>
  <Wrapper>
    <Tabs.Panel />
  </Wrapper>
</Tabs>
```

### 💡 Why:

Context works across entire subtree

***

## 18. What are real-world scenarios where compound components shine?

### ✅ Answer

* Tabs
* Dropdown menus
* Modals
* Accordions
* Design systems

### 💡 Why:

These require:

* Shared state
* Flexible UI structure

***

## 🔚 Final Insight

At a senior level, compound components are about:

* **Designing flexible APIs**
* **Balancing abstraction vs clarity**
* **Managing shared state efficiently**

***

👉 Strong engineers understand:

* When to use compound components
* When to replace with hooks or simpler patterns
* How to avoid performance pitfalls

***

# 🧠 Senior-Level MCQs — Compound Components (Deep Understanding)

***

## 1. What is the most critical reason compound components rely on Context?

### Options:

A. To improve rendering performance
B. To avoid prop drilling and enable deep composition
C. To replace hooks
D. To enforce strict component hierarchy

### ✅ Correct Answer: **B**

### 💡 Explanation:

Compound components need to share state across deeply nested children. Context enables this without manually passing props.

### ❌ Why others are wrong:

* A: Context can hurt performance if misused
* C: Hooks and context serve different purposes
* D: Context doesn’t enforce hierarchy

***

## 2. What happens if a compound child component is rendered outside its parent?

```js id="q1" theme={null}
<Tabs.Tab />
```

### Options:

A. React throws compile error
B. It works but without state
C. Context becomes undefined → runtime issues
D. React automatically wraps it

### ✅ Correct Answer: **C**

### 💡 Explanation:

Without a provider, `useContext` returns `undefined`, causing runtime errors.

### ❌ Why others are wrong:

* A: No compile-time check
* B: Usually crashes or behaves incorrectly
* D: React doesn’t auto-wrap

***

## 3. Why is `React.cloneElement` not ideal for scalable compound components?

### Options:

A. It is deprecated
B. It only works for direct children
C. It is slower than context
D. It breaks JSX

### ✅ Correct Answer: **B**

### 💡 Explanation:

`cloneElement` cannot handle deeply nested children effectively.

### ❌ Why others are wrong:

* A: Not deprecated
* C: Not the main limitation
* D: JSX works fine

***

## 4. What is the biggest performance issue with Context in compound components?

### Options:

A. Memory leaks
B. All consumers re-render on value change
C. Infinite loops
D. Blocking rendering

### ✅ Correct Answer: **B**

### 💡 Explanation:

Any change in context value triggers re-render of all consuming components.

### ❌ Why others are wrong:

* A: Not inherent
* C: Not typical
* D: Incorrect

***

## 5. Why is index-based coordination risky in compound components?

### Options:

A. Slows rendering
B. Breaks when children reorder
C. Causes infinite loops
D. Not supported by React

### ✅ Correct Answer: **B**

### 💡 Explanation:

Indexes are unstable → UI breaks when order changes.

### ❌ Why others are wrong:

* A: Not main issue
* C: Not related
* D: Supported

***

## 6. What is a subtle bug when context value is not memoized?

```js id="q6" theme={null}
<Provider value={{ active }}>
```

### Options:

A. Infinite loop
B. Unnecessary re-renders
C. Memory leak
D. Hook violation

### ✅ Correct Answer: **B**

### 💡 Explanation:

New object each render → context updates → all consumers re-render.

### ❌ Why others are wrong:

* A: No loop
* C: Not a leak
* D: No hook violation

***

## 7. What architectural advantage do compound components provide?

### Options:

A. Faster rendering
B. Declarative UI composition
C. Smaller bundle size
D. Automatic memoization

### ✅ Correct Answer: **B**

### 💡 Explanation:

They enable flexible, declarative APIs via composition.

### ❌ Why others are wrong:

* A: Not guaranteed
* C: Not related
* D: Not automatic

***

## 8. Why can compound components lead to implicit coupling?

### Options:

A. They share global state
B. Child components depend on parent context
C. They use hooks
D. They are nested

### ✅ Correct Answer: **B**

### 💡 Explanation:

Children rely on hidden context → tightly coupled with parent.

### ❌ Why others are wrong:

* A: Context is scoped
* C: Not relevant
* D: Nesting alone isn’t the issue

***

## 9. What happens if context provider value changes frequently?

### Options:

A. Nothing
B. Only parent re-renders
C. All consumers re-render
D. React skips updates

### ✅ Correct Answer: **C**

### 💡 Explanation:

Context triggers re-render for all consumers.

***

## 10. What is the main difference between compound components and render props?

### Options:

A. Render props are faster
B. Compound components are more declarative
C. Render props cannot share state
D. Compound components cannot nest

### ✅ Correct Answer: **B**

### 💡 Explanation:

Compound components provide cleaner, declarative APIs.

***

## 11. What is a common bug when using compound components with dynamic children?

### Options:

A. Hook violation
B. State mismatch due to unstable keys
C. Memory leak
D. Syntax error

### ✅ Correct Answer: **B**

### 💡 Explanation:

Changing order or keys → state mismatches.

***

## 12. Why is validating context usage important?

### Options:

A. Improves performance
B. Prevents usage outside provider
C. Reduces bundle size
D. Required by React

### ✅ Correct Answer: **B**

### 💡 Explanation:

Prevents runtime errors when used incorrectly.

***

## 13. What is the main drawback of compound components vs hooks?

### Options:

A. Cannot share logic
B. More structural complexity
C. Slower rendering
D. Cannot use context

### ✅ Correct Answer: **B**

### 💡 Explanation:

Requires structured component hierarchy.

***

## 14. What happens when compound components are deeply nested?

### Options:

A. Breaks context
B. Still works due to context propagation
C. Causes memory leak
D. Stops rendering

### ✅ Correct Answer: **B**

### 💡 Explanation:

Context works across entire subtree.

***

## 15. Why should compound components support controlled mode?

### Options:

A. Improve performance
B. Allow external state control
C. Reduce code size
D. Avoid context

### ✅ Correct Answer: **B**

### 💡 Explanation:

Allows parent components to control behavior.

***

## 16. What is a subtle bug when mixing controlled and uncontrolled modes?

### Options:

A. Syntax error
B. State inconsistency
C. Infinite loop
D. Memory leak

### ✅ Correct Answer: **B**

### 💡 Explanation:

Conflicting sources of truth cause inconsistent UI.

***

## 17. Why is splitting context sometimes necessary?

### Options:

A. To reduce bundle size
B. To reduce unnecessary re-renders
C. To support hooks
D. To improve syntax

### ✅ Correct Answer: **B**

### 💡 Explanation:

Separate state/actions → fewer re-renders.

***

## 18. What is the main reason compound components are popular in design systems?

### Options:

A. Faster rendering
B. Better UI flexibility and composability
C. Smaller codebase
D. Easier debugging

### ✅ Correct Answer: **B**

### 💡 Explanation:

They enable flexible UI composition for reusable components.

***

# 🔚 Final Insight

These MCQs test:

* Context behavior
* Performance pitfalls
* API design thinking
* Real-world edge cases

***

👉 Senior-level takeaway:
Compound components are about:

* **Designing APIs, not just components**
* **Balancing flexibility vs complexity**
* **Managing shared state efficiently**

***

# 🧠 Compound Components — Real-World Coding Problems (Senior Level)

***

## 1. 🟡 Tabs System (Basic → Extensible)

### 📌 Problem

Build a `<Tabs>` compound component with `<Tabs.Tab>` and `<Tabs.Panel>`.

### Constraints

* Shared state via context
* Flexible ordering of children

### Expected Behavior

```js id="cc1" theme={null}
<Tabs>
  <Tabs.Tab id="1">Tab 1</Tabs.Tab>
  <Tabs.Tab id="2">Tab 2</Tabs.Tab>

  <Tabs.Panel id="1">Content 1</Tabs.Panel>
  <Tabs.Panel id="2">Content 2</Tabs.Panel>
</Tabs>
```

### Edge Cases

* Tabs without panels
* Duplicate IDs
* Dynamic tab addition

### 🪜 Solution Approach

1. Create context for `activeId`
2. Provide setter in parent
3. Tabs update state
4. Panels render conditionally

***

## 2. 🟡 Accordion (Single/Multiple Expand)

### 📌 Problem

Build `<Accordion>` with `<Item>`, `<Header>`, `<Content>`

### Constraints

* Support both single and multiple open items

### Edge Cases

* Toggling same item
* Controlled vs uncontrolled

### 🪜 Approach

* Store open IDs (array or single value)
* Context for shared state

***

## 3. 🟠 Dropdown Menu System

### 📌 Problem

Create:

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

### Constraints

* Close on outside click
* Keyboard navigation

### Edge Cases

* Nested dropdowns
* Focus management

### 🪜 Approach

* Track open state
* Handle events globally

***

## 4. 🟠 Modal System

### 📌 Problem

Build compound modal API:

```js id="cc4" theme={null}
<Modal>
  <Modal.Trigger />
  <Modal.Content />
</Modal>
```

### Constraints

* Support multiple modals
* Manage focus trap

### Edge Cases

* Escape key
* Scroll locking

***

## 5. 🟠 Form Field Group

### 📌 Problem

Build:

```js id="cc5" theme={null}
<FormField>
  <FormField.Label />
  <FormField.Input />
  <FormField.Error />
</FormField>
```

### Constraints

* Validation state shared

### Edge Cases

* Async validation
* Error priority

***

## 6. 🔴 Stepper / Wizard

### 📌 Problem

Multi-step form navigation

```js id="cc6" theme={null}
<Stepper>
  <Stepper.Step />
</Stepper>
```

### Constraints

* Validation before moving forward

### Edge Cases

* Skipping steps
* Reset flow

***

## 7. 🔴 Menu with Nested Items

### 📌 Problem

Support deeply nested menus

### Constraints

* Context should propagate deeply

### Edge Cases

* Recursive rendering

***

## 8. 🔴 Tooltip System

### 📌 Problem

Compound tooltip:

```js id="cc8" theme={null}
<Tooltip>
  <Tooltip.Trigger />
  <Tooltip.Content />
</Tooltip>
```

### Constraints

* Positioning logic

### Edge Cases

* Hover flickering

***

## 9. 🔴 Tabs with Lazy Loading Panels

### 📌 Problem

Load panel content only when active

### Edge Cases

* Switching tabs rapidly

### 🪜 Approach

* Track visited tabs

***

## 10. 🔴 Data Table with Sorting

### 📌 Problem

```js id="cc10" theme={null}
<Table>
  <Table.Header />
  <Table.Row />
</Table>
```

### Constraints

* Sorting logic centralized

### Edge Cases

* Large datasets

***

## 11. 🔴 Notification System

### 📌 Problem

Global notification manager

### Constraints

* Add/remove dynamically

### Edge Cases

* Auto-dismiss

***

## 12. 🔴 Carousel / Slider

### 📌 Problem

```js id="cc12" theme={null}
<Carousel>
  <Carousel.Item />
</Carousel>
```

### Constraints

* Auto-play
* Swipe support

***

## 13. 🔴 Tree View Component

### 📌 Problem

Nested expandable tree

### Edge Cases

* Deep recursion
* Performance

***

## 14. 🔴 Select / Combobox

### 📌 Problem

Accessible dropdown with search

### Constraints

* Keyboard navigation

***

## 15. 🔴 Tabs with Controlled + Uncontrolled Mode

### 📌 Problem

Allow external control:

```js id="cc15" theme={null}
<Tabs activeId="1" onChange={...} />
```

### Edge Cases

* Switching modes dynamically

***

## 16. 🔴 Context Split Optimization

### 📌 Problem

Optimize compound component with multiple contexts

### Constraints

* Prevent unnecessary re-renders

***

## 17. 🔴 Drag-and-Drop List

### 📌 Problem

Compound draggable list

### Constraints

* Reordering

***

## 18. 🔴 Multi-Select Dropdown

### 📌 Problem

Select multiple options

### Edge Cases

* Large lists

***

## 19. 🔴 Permission-Based UI Sections

### 📌 Problem

Hide/show components based on roles

***

## 🔚 Final Insight

These problems test:

* Context design
* API ergonomics
* Performance optimization
* Real-world UI architecture

***

👉 Senior-level expectation:
You should:

* Design flexible APIs
* Handle edge cases
* Optimize context usage
* Balance abstraction vs usability

***

# 🛠️ Senior Code Review — Compound Components Debugging Challenges

***

## 1. ❗ Using Child Outside Provider

```js theme={null}
function Tab() {
  const { activeId } = useContext(TabsContext);
  return <div>{activeId}</div>;
}

// Usage
<Tab /> // ❌ outside Tabs
```

### 🔍 What’s wrong?

`Tab` is used outside its context provider.

### 💡 Why it happens

`useContext` returns `undefined` → destructuring fails.

### ✅ Fix

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

  const { activeId } = context;
  return <div>{activeId}</div>;
}
```

### 🧠 Best Practice

Always validate context usage.

***

## 2. ❗ Context Value Not Memoized

```js theme={null}
<TabsContext.Provider value={{ activeId, setActiveId }}>
```

### 🔍 What’s wrong?

New object every render.

### 💡 Why

Triggers re-render of all consumers.

### ✅ Fix

```js theme={null}
const value = useMemo(() => ({ activeId, setActiveId }), [activeId]);
<TabsContext.Provider value={value}>
```

### 🧠 Best Practice

Memoize context values.

***

## 3. ❗ Index-Based Logic Breaks on Reorder

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

### 🔍 What’s wrong?

Reordering breaks mapping.

### 💡 Why

Indexes are unstable identifiers.

### ✅ Fix

```js theme={null}
<Tab id="tab-1" />
<Tab id="tab-2" />
```

### 🧠 Best Practice

Use stable IDs instead of indexes.

***

## 4. ❗ All Consumers Re-render on Any State Change

```js theme={null}
const value = { activeId, setActiveId };
```

### 🔍 What’s wrong?

Every update re-renders all consumers.

### 💡 Why

Single context holds both state and actions.

### ✅ Fix

```js theme={null}
const StateContext = createContext();
const ActionsContext = createContext();
```

### 🧠 Best Practice

Split context for performance.

***

## 5. ❗ Missing Dependency in Effect

```js theme={null}
useEffect(() => {
  setActiveId(props.defaultId);
}, []);
```

### 🔍 What’s wrong?

Doesn’t update when `defaultId` changes.

### 💡 Why

Dependency array is incomplete.

### ✅ Fix

```js theme={null}
useEffect(() => {
  setActiveId(props.defaultId);
}, [props.defaultId]);
```

***

## 6. ❗ Incorrect Controlled/Uncontrolled Handling

```js theme={null}
const [activeId, setActiveId] = useState(props.activeId);
```

### 🔍 What’s wrong?

State doesn’t update when prop changes.

### 💡 Why

`useState` only runs on initial render.

### ✅ Fix

```js theme={null}
const isControlled = props.activeId !== undefined;
const activeId = isControlled ? props.activeId : internalState;
```

***

## 7. ❗ Deeply Nested Components Not Receiving Context

```js theme={null}
React.cloneElement(children, { activeId });
```

### 🔍 What’s wrong?

Only direct children get props.

### 💡 Why

`cloneElement` doesn’t propagate deeply.

### ✅ Fix

Use context instead.

***

## 8. ❗ Mutating Context Value

```js theme={null}
context.activeId = newId; // ❌
```

### 🔍 What’s wrong?

Mutates state directly.

### 💡 Why

Breaks React state model.

### ✅ Fix

```js theme={null}
setActiveId(newId);
```

***

## 9. ❗ Conditional Hook Usage

```js theme={null}
if (isActive) {
  const context = useContext(TabsContext); // ❌
}
```

### 🔍 What’s wrong?

Violates Rules of Hooks.

### 💡 Why

Hooks must run consistently.

### ✅ Fix

```js theme={null}
const context = useContext(TabsContext);
```

***

## 10. ❗ Component Order Dependency Bug

```js theme={null}
<Tabs.Panel id="1" />
<Tabs.Tab id="1" />
```

### 🔍 What’s wrong?

UI logic assumes order.

### 💡 Why

Implicit assumptions about structure.

### ✅ Fix

Decouple logic from order.

***

## 11. ❗ Expensive Computation in Consumer

```js theme={null}
const result = heavyComputation(context.data);
```

### 🔍 What’s wrong?

Runs every render.

### 💡 Why

No memoization.

### ✅ Fix

```js theme={null}
const result = useMemo(() => heavyComputation(data), [data]);
```

***

## 12. ❗ Missing Key in Dynamic Children

```js theme={null}
{items.map(item => <Tabs.Tab id={item.id} />)}
```

### 🔍 What’s wrong?

Missing `key`.

### 💡 Why

Breaks reconciliation.

### ✅ Fix

```js theme={null}
key={item.id}
```

***

## 13. ❗ Uncontrolled State Reset on Re-render

```js theme={null}
const [open, setOpen] = useState(false);
```

### 🔍 What’s wrong?

State resets when parent re-renders with new key.

### 💡 Why

Component remounts.

### ✅ Fix

Avoid unnecessary key changes.

***

## 14. ❗ Multiple Providers Causing State Isolation

```js theme={null}
<Tabs>
  <Tabs>
    <Tabs.Tab />
  </Tabs>
</Tabs>
```

### 🔍 What’s wrong?

Nested providers isolate state.

### 💡 Why

Each provider has separate state.

### ✅ Fix

Avoid unintended nesting.

***

## 15. ❗ Context Value Changing Too Frequently

```js theme={null}
const value = { activeId, timestamp: Date.now() };
```

### 🔍 What’s wrong?

Always changes → re-renders.

### 💡 Why

New value every render.

### ✅ Fix

Remove unstable values.

***

## 16. ❗ Event Handler Recreated Every Render

```js theme={null}
<button onClick={() => setActiveId(id)} />
```

### 🔍 What’s wrong?

New function each render.

### 💡 Why

Breaks memoized children.

### ✅ Fix

```js theme={null}
const handleClick = useCallback(() => setActiveId(id), [id]);
```

***

## 17. ❗ Incorrect Default Context Value

```js theme={null}
const TabsContext = createContext({});
```

### 🔍 What’s wrong?

Empty object hides errors.

### 💡 Why

Accessing undefined fields silently fails.

### ✅ Fix

```js theme={null}
const TabsContext = createContext(null);
```

***

## 🔚 Final Takeaway

These bugs highlight:

* Context misuse
* Performance pitfalls
* Structural assumptions
* State synchronization issues

***

👉 Senior-level expectation:
You should be able to:

* Predict re-render behavior
* Design efficient context systems
* Debug implicit coupling issues

***

# 🧠 Senior Frontend Architect — Compound Components Machine Coding Problems

***

## 1. 🔴 Advanced Tabs System (Accessible + Extensible)

### 📌 Requirements

* Build `<Tabs>` with `<Tabs.List>`, `<Tabs.Tab>`, `<Tabs.Panel>`
* Support keyboard navigation (Arrow keys, Enter)
* Controlled + uncontrolled modes
* ARIA accessibility

### 🖥️ UI Behavior

* Active tab highlighted
* Panel switches instantly
* Keyboard navigation cycles tabs

### 🔄 State/Data Flow

* `activeId` managed in parent → context → consumed by children

### ⚠️ Edge Cases

* Dynamic tab addition/removal
* Duplicate IDs
* SSR hydration mismatch

### ⚡ Performance

* Memoize context value
* Avoid re-rendering all panels

### 🏗️ Architecture

* Context for state
* Subcomponents attached to parent

### 🪜 Approach

1. Create context (`activeId`, `setActiveId`)
2. Implement controlled/uncontrolled logic
3. Handle keyboard events
4. Conditionally render panels

***

## 2. 🔴 Headless Dropdown / Menu System

### 📌 Requirements

* Build fully accessible dropdown
* Components: `Trigger`, `Menu`, `Item`
* Support keyboard + mouse interactions

### 🖥️ UI Behavior

* Click/Enter opens menu
* Arrow keys navigate items
* Escape closes menu

### 🔄 Data Flow

* Open state → context → children

### ⚠️ Edge Cases

* Nested dropdowns
* Click outside detection

### ⚡ Performance

* Debounce event listeners
* Avoid unnecessary re-renders

### 🪜 Approach

1. Track open state
2. Manage focus index
3. Handle global events
4. Provide context to children

***

## 3. 🔴 Modal System with Portal + Stack

### 📌 Requirements

* Support multiple modals (stacked)
* Provide `Trigger`, `Content`, `Overlay`

### 🖥️ UI Behavior

* Background scroll lock
* Escape closes top modal

### ⚠️ Edge Cases

* Nested modals
* Focus trap

### ⚡ Performance

* Minimize re-renders of entire tree

### 🏗️ Architecture

* Context + Portal

### 🪜 Approach

1. Maintain modal stack
2. Render using `ReactDOM.createPortal`
3. Manage focus trap

***

## 4. 🔴 Form System (Compound + Validation Engine)

### 📌 Requirements

* `<Form>`, `<Field>`, `<Label>`, `<Error>`
* Centralized validation

### 🔄 Data Flow

* Form state → context → fields

### ⚠️ Edge Cases

* Async validation
* Dynamic fields

### ⚡ Performance

* Field-level updates only

### 🪜 Approach

1. Store form state centrally
2. Provide validation API
3. Allow fields to subscribe selectively

***

## 5. 🔴 Multi-Step Wizard with Guards

### 📌 Requirements

* Step navigation with validation guards
* Support skipping/branching

### 🖥️ UI Behavior

* Next disabled until valid
* Progress indicator

### ⚠️ Edge Cases

* Back navigation
* Reset flow

### 🪜 Approach

1. Maintain step index
2. Store step metadata
3. Validate before advancing

***

## 6. 🔴 Data Table (Sorting + Filtering + Pagination)

### 📌 Requirements

* `<Table>`, `<Header>`, `<Row>`, `<Cell>`
* Sorting + filtering logic centralized

### ⚠️ Edge Cases

* Large datasets
* Column reordering

### ⚡ Performance

* Memoize filtered/sorted data

***

## 7. 🔴 Accordion (Single + Multi Expand)

### 📌 Requirements

* Support both modes

### ⚠️ Edge Cases

* Rapid toggling
* Controlled mode

***

## 8. 🔴 Tooltip System (Positioning Engine)

### 📌 Requirements

* Position tooltip relative to trigger
* Support hover, focus, click

### ⚠️ Edge Cases

* Viewport overflow
* Flickering

### ⚡ Performance

* Use `requestAnimationFrame`

***

## 9. 🔴 Tree View (Recursive Compound Component)

### 📌 Requirements

* Expand/collapse nested nodes

### ⚠️ Edge Cases

* Deep recursion
* Lazy loading children

***

## 10. 🔴 Combobox (Searchable Select)

### 📌 Requirements

* Search + keyboard navigation

### ⚠️ Edge Cases

* Large dataset
* Async search

***

## 11. 🔴 Notification System (Global + Scoped)

### 📌 Requirements

* Trigger notifications from anywhere

### ⚠️ Edge Cases

* Auto-dismiss
* Queue overflow

***

## 12. 🔴 Carousel (Auto-play + Controls)

### 📌 Requirements

* Swipe + auto-play

### ⚠️ Edge Cases

* Rapid swipes
* Looping

***

## 13. 🔴 Drag-and-Drop List

### 📌 Requirements

* Reorder items via drag

### ⚠️ Edge Cases

* Drop outside
* Accessibility

***

## 14. 🔴 Sidebar Navigation System

### 📌 Requirements

* Collapsible sections

### ⚠️ Edge Cases

* Nested navigation

***

## 15. 🔴 Multi-Select Dropdown

### 📌 Requirements

* Select multiple items
* Show selected tags

### ⚠️ Edge Cases

* Large list
* Duplicate selection

***

## 16. 🔴 Context Splitting Optimization Problem

### 📌 Requirements

* Optimize large compound component tree

### ⚠️ Edge Cases

* Frequent updates

### 🪜 Approach

* Split state and actions into separate contexts

***

## 17. 🔴 Permission-Based Layout System

### 📌 Requirements

* Show/hide UI based on roles

### ⚠️ Edge Cases

* Dynamic role updates

***

## 18. 🔴 Virtualized List with Compound API

### 📌 Requirements

* Render large list efficiently

### ⚠️ Edge Cases

* Dynamic heights

### ⚡ Performance

* Windowing

***

## 19. 🔴 Global Theme Provider with Scoped Overrides

### 📌 Requirements

* Theme context with overrides

### ⚠️ Edge Cases

* Nested themes

***

# 🔚 Final Insight

These problems simulate:

* Design system components
* Headless UI architecture
* Performance-sensitive systems

***

👉 Senior-level expectations:

You should be able to:

* Design **flexible APIs**
* Handle **complex state sharing**
* Optimize **context performance**
* Think in **systems, not components**

***

# 🧠 FAANG-Level Frontend Interview — Compound Components

***

## 1. When would you choose compound components over a props-based API?

### 🔍 Follow-up:

* What are the trade-offs?
* When would props be better?

### ✅ Strong Answer:

* Choose compound components when:

  * UI structure must be **flexible and composable**
  * Multiple parts share **implicit state**
* Props-based APIs are better when:

  * Structure is fixed
  * Simpler components

👉 Compound components shift from **configuration → composition**

### ❌ Weak Answer:

> “Compound components are cleaner”

👉 Fails because:

* Doesn’t explain trade-offs or use-case

***

## 2. How do compound components work under the hood?

### 🔍 Follow-up:

* Why is context typically required?

### ✅ Strong Answer:

* Parent manages state
* Context provides shared data
* Children consume via `useContext`

```js theme={null}
const value = useContext(Context);
```

👉 Enables implicit communication

### ❌ Weak Answer:

> “They share state”

👉 Fails because:

* No explanation of mechanism

***

## 3. What are the performance implications of using Context in compound components?

### 🔍 Follow-up:

* How would you optimize?

### ✅ Strong Answer:

* Context updates → all consumers re-render
* Optimization:

  * Memoize value
  * Split contexts
  * Use selectors

### ❌ Weak Answer:

> “Context is fast”

👉 Fails because:

* Ignores re-render cost

***

## 4. Why is `React.cloneElement` not a scalable solution for compound components?

### 🔍 Follow-up:

* When is it acceptable?

### ✅ Strong Answer:

* Only works for direct children
* Breaks with deep nesting
* Hard to maintain

👉 Context is more scalable

### ❌ Weak Answer:

> “It’s outdated”

👉 Fails because:

* Not technically accurate

***

## 5. What is implicit coupling in compound components?

### 🔍 Follow-up:

* How can it become problematic?

### ✅ Strong Answer:

* Children depend on hidden context
* Cannot work independently

👉 Leads to:

* Hard debugging
* Tight coupling

### ❌ Weak Answer:

> “Components are connected”

👉 Fails because:

* Too vague

***

## 6. How would you design a robust Tabs compound component?

### 🔍 Follow-up:

* How do you handle accessibility?

### ✅ Strong Answer:

* Use context for state
* Provide `Tab`, `Panel`
* Support:

  * Keyboard navigation
  * ARIA roles
  * Controlled/uncontrolled mode

### ❌ Weak Answer:

> “Use useState”

👉 Fails because:

* Too shallow

***

## 7. What are common bugs when using compound components?

### 🔍 Follow-up:

* How do you prevent them?

### ✅ Strong Answer:

* Using child outside provider
* Context not memoized
* Index-based bugs
* Controlled/uncontrolled conflicts

### ❌ Weak Answer:

> “Context issues”

👉 Fails because:

* Not specific

***

## 8. How do compound components enable inversion of control?

### 🔍 Follow-up:

* Compare with render props

### ✅ Strong Answer:

* Parent handles logic
* Consumer controls layout

👉 Example:

```js theme={null}
<Tabs>
  <CustomLayout />
</Tabs>
```

### ❌ Weak Answer:

> “Parent controls children”

👉 Fails because:

* Incorrect understanding

***

## 9. How would you debug a compound component not updating correctly?

### 🔍 Follow-up:

* What tools would you use?

### ✅ Strong Answer:

1. Check context value updates
2. Verify provider hierarchy
3. Inspect re-renders in DevTools
4. Check memoization issues

### ❌ Weak Answer:

> “Add console logs”

👉 Fails because:

* No structured debugging

***

## 10. What are the trade-offs between compound components and hooks?

### 🔍 Follow-up:

* Can they be combined?

### ✅ Strong Answer:

* Hooks:

  * Logic reuse
* Compound:

  * UI composition

👉 Often combined:

```js theme={null}
const data = useTabs();
```

### ❌ Weak Answer:

> “Hooks are better”

👉 Fails because:

* No comparison

***

## 11. How would you design compound components for scalability in a design system?

### 🔍 Follow-up:

* API design principles?

### ✅ Strong Answer:

* Clear naming (`Tabs.List`, `Tabs.Panel`)
* Minimal required props
* Context-based architecture
* Controlled/uncontrolled support

### ❌ Weak Answer:

> “Make reusable components”

👉 Fails because:

* Too generic

***

## 12. Why is controlled vs uncontrolled state important?

### 🔍 Follow-up:

* What bugs occur if mishandled?

### ✅ Strong Answer:

* Allows external control
* Bugs:

  * Conflicting sources of truth
  * State mismatch

### ❌ Weak Answer:

> “For flexibility”

👉 Fails because:

* No depth

***

## 13. How do compound components behave with deeply nested children?

### 🔍 Follow-up:

* Why does this work?

### ✅ Strong Answer:

* Context propagates through entire tree
* Works regardless of nesting depth

### ❌ Weak Answer:

> “They just work”

👉 Fails because:

* No explanation

***

## 14. What are architectural drawbacks of compound components?

### 🔍 Follow-up:

* When should you avoid them?

### ✅ Strong Answer:

* Implicit coupling
* Performance issues
* Structural complexity

Avoid when:

* Simple components
* No shared state needed

### ❌ Weak Answer:

> “They are complex”

👉 Fails because:

* No reasoning

***

## 15. How do you prevent unnecessary re-renders in compound components?

### 🔍 Follow-up:

* Advanced strategies?

### ✅ Strong Answer:

* Memoize context value
* Split contexts
* Use `React.memo`
* Avoid passing new objects

### ❌ Weak Answer:

> “Use memo”

👉 Fails because:

* Lacks depth

***

## 16. What is a real-world scenario where compound components shine?

### 🔍 Follow-up:

* Why not use props?

### ✅ Strong Answer:

* Tabs, Dropdowns, Modals
* Require:

  * Shared state
  * Flexible layout

### ❌ Weak Answer:

> “UI components”

👉 Fails because:

* Too broad

***

## 17. How would you test compound components?

### 🔍 Follow-up:

* What should be verified?

### ✅ Strong Answer:

* Context propagation
* State updates
* Rendering logic

### ❌ Weak Answer:

> “Test UI”

👉 Fails because:

* Ignores internal logic

***

## 18. What happens if context value changes too frequently?

### 🔍 Follow-up:

* How to fix?

### ✅ Strong Answer:

* All consumers re-render
* Fix:

  * Memoization
  * Context splitting

### ❌ Weak Answer:

> “It updates”

👉 Fails because:

* No performance awareness

***

## 19. How do you ensure good developer experience (DX) with compound components?

### 🔍 Follow-up:

* What API design choices matter?

### ✅ Strong Answer:

* Clear naming
* Good defaults
* Runtime validations
* Helpful error messages

### ❌ Weak Answer:

> “Make it simple”

👉 Fails because:

* Not actionable

***

# 🔚 Final Insight

At FAANG-level, compound components are evaluated as:

* A **UI composition pattern**
* A **design system building block**
* A **trade-off between flexibility and complexity**

***

👉 Strong candidates:

* Understand **when to use vs avoid**
* Optimize **context performance**
* Design **clean, scalable APIs**

***
