Skip to main content

πŸ“˜ 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)

πŸ‘‰ 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

πŸ”Ή 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
πŸ‘‰ Why?
  • Avoid prop drilling
  • Allow deep nesting

πŸ”Ή 4. Implicit Communication

Child components don’t receive explicit props like:
Instead:
  • They derive state from context

πŸ”Ή 5. Component Composition

Compound components leverage:
Composition over configuration
Instead of:
You write:

πŸ”Ή 6. Relationship with Other Patterns

πŸ‘‰ Compound components = UI-level abstraction

3. πŸ§ͺ Syntax & Examples


πŸ”Ή Example 1: Tabs (Core Example)

Step 1: Create Context


Step 2: Parent Component


Step 3: Tab Component


Step 4: Panel Component


Step 5: Attach Subcomponents


Usage:


πŸ”Ή Example 2: Accordion


πŸ”Ή Example 3: Dropdown


πŸ”Ή Variation: Without Context (Less Flexible)

πŸ‘‰ Works, but:
  • Harder to scale
  • Limited nesting

4. ⚠️ Edge Cases / Common Mistakes


πŸ”Ή 1. Using Component Outside Parent

Problem:

  • useContext returns undefined

βœ… Fix:


πŸ”Ή 2. Overusing Context (Performance Issues)

  • Every context update β†’ re-renders all consumers

βœ… Fix:

  • Split contexts
  • Memoize values

πŸ”Ή 3. Index-Based Logic Bugs

πŸ‘‰ 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

πŸ‘‰ Order mismatch β†’ incorrect UI

πŸ”Ή 7. Uncontrolled vs Controlled State

πŸ‘‰ Sometimes you need both:

5. βœ… Best Practices


πŸ”Ή 1. Use Context for Shared State

βœ” Avoid prop drilling βœ” Enable flexible composition

πŸ”Ή 2. Validate Usage


πŸ”Ή 3. Keep API Declarative

βœ” Prefer:
❌ Avoid:

πŸ”Ή 4. Support Controlled + Uncontrolled


πŸ”Ή 5. Memoize Context Value


πŸ”Ή 6. Split Contexts for Performance

  • One for state
  • One for actions

πŸ”Ή 7. Use Clear Naming


πŸ”Ή 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:

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

🟒 Compound Components Solution:

πŸ’‘ Why:

  • Moves from configuration β†’ composition
  • Gives full control over layout

πŸ” Comparison:


2. How do compound components work internally in React?

βœ… Answer

They rely on:
  1. Shared state (parent)
  2. Context API
  3. Implicit communication
Children:

πŸ’‘ 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:

❌ 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

5. How do compound components enable inversion of control?

βœ… Answer

Parent:
  • Manages logic
Consumer:
  • Controls structure and layout

πŸ’‘ Why:

  • Consumer decides UI
  • Parent only provides behavior

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

βœ… Answer

πŸ’‘ 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

πŸ’‘ Insight:

  • Hooks handle logic
  • Compound components handle UI structure
πŸ‘‰ Often used together

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

βœ… Answer

πŸ”΄ Problem:

  • No context provider β†’ undefined

πŸ’‘ Why:

Context is required for communication

🟒 Fix:


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

βœ… Answer

πŸ”΄ 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

πŸ’‘ 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

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:

πŸ’‘ 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?

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?

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.

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

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:

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:

Constraints

  • Support multiple modals
  • Manage focus trap

Edge Cases

  • Escape key
  • Scroll locking

5. 🟠 Form Field Group

πŸ“Œ Problem

Build:

Constraints

  • Validation state shared

Edge Cases

  • Async validation
  • Error priority

6. πŸ”΄ Stepper / Wizard

πŸ“Œ Problem

Multi-step form navigation

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:

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

Constraints

  • Sorting logic centralized

Edge Cases

  • Large datasets

11. πŸ”΄ Notification System

πŸ“Œ Problem

Global notification manager

Constraints

  • Add/remove dynamically

Edge Cases

  • Auto-dismiss

πŸ“Œ Problem

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:

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

πŸ” What’s wrong?

Tab is used outside its context provider.

πŸ’‘ Why it happens

useContext returns undefined β†’ destructuring fails.

βœ… Fix

🧠 Best Practice

Always validate context usage.

2. ❗ Context Value Not Memoized

πŸ” What’s wrong?

New object every render.

πŸ’‘ Why

Triggers re-render of all consumers.

βœ… Fix

🧠 Best Practice

Memoize context values.

3. ❗ Index-Based Logic Breaks on Reorder

πŸ” What’s wrong?

Reordering breaks mapping.

πŸ’‘ Why

Indexes are unstable identifiers.

βœ… Fix

🧠 Best Practice

Use stable IDs instead of indexes.

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

πŸ” What’s wrong?

Every update re-renders all consumers.

πŸ’‘ Why

Single context holds both state and actions.

βœ… Fix

🧠 Best Practice

Split context for performance.

5. ❗ Missing Dependency in Effect

πŸ” What’s wrong?

Doesn’t update when defaultId changes.

πŸ’‘ Why

Dependency array is incomplete.

βœ… Fix


6. ❗ Incorrect Controlled/Uncontrolled Handling

πŸ” What’s wrong?

State doesn’t update when prop changes.

πŸ’‘ Why

useState only runs on initial render.

βœ… Fix


7. ❗ Deeply Nested Components Not Receiving Context

πŸ” What’s wrong?

Only direct children get props.

πŸ’‘ Why

cloneElement doesn’t propagate deeply.

βœ… Fix

Use context instead.

8. ❗ Mutating Context Value

πŸ” What’s wrong?

Mutates state directly.

πŸ’‘ Why

Breaks React state model.

βœ… Fix


9. ❗ Conditional Hook Usage

πŸ” What’s wrong?

Violates Rules of Hooks.

πŸ’‘ Why

Hooks must run consistently.

βœ… Fix


10. ❗ Component Order Dependency Bug

πŸ” What’s wrong?

UI logic assumes order.

πŸ’‘ Why

Implicit assumptions about structure.

βœ… Fix

Decouple logic from order.

11. ❗ Expensive Computation in Consumer

πŸ” What’s wrong?

Runs every render.

πŸ’‘ Why

No memoization.

βœ… Fix


12. ❗ Missing Key in Dynamic Children

πŸ” What’s wrong?

Missing key.

πŸ’‘ Why

Breaks reconciliation.

βœ… Fix


13. ❗ Uncontrolled State Reset on Re-render

πŸ” 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

πŸ” What’s wrong?

Nested providers isolate state.

πŸ’‘ Why

Each provider has separate state.

βœ… Fix

Avoid unintended nesting.

15. ❗ Context Value Changing Too Frequently

πŸ” What’s wrong?

Always changes β†’ re-renders.

πŸ’‘ Why

New value every render.

βœ… Fix

Remove unstable values.

16. ❗ Event Handler Recreated Every Render

πŸ” What’s wrong?

New function each render.

πŸ’‘ Why

Breaks memoized children.

βœ… Fix


17. ❗ Incorrect Default Context Value

πŸ” What’s wrong?

Empty object hides errors.

πŸ’‘ Why

Accessing undefined fields silently fails.

βœ… Fix


πŸ”š 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

πŸ“Œ 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
πŸ‘‰ 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:

❌ 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:

❌ 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