๐ 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
Compound components = a group of components that share logic and state internally but expose a flexible API externally
๐น Example (Mental Model)
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
- 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- Avoid prop drilling
- Allow deep nesting
๐น 4. Implicit Communication
Child components donโt receive explicit props like:- They derive state from context
๐น 5. Component Composition
Compound components leverage:Composition over configurationInstead of:
๐น 6. Relationship with Other Patterns
| Pattern | Relationship |
|---|---|
| HOC | Structural reuse |
| Render Props | Logic sharing |
| Hooks | Internal logic |
| Compound Components | UI composition |
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)
- Harder to scale
- Limited nesting
4. โ ๏ธ Edge Cases / Common Mistakes
๐น 1. Using Component Outside Parent
Problem:
useContextreturns undefined
โ Fix:
๐น 2. Overusing Context (Performance Issues)
- Every context update โ re-renders all consumers
โ Fix:
- Split contexts
- Memoize values
๐น 3. Index-Based Logic Bugs
โ 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
๐น 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:๐น 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:
| Approach | Limitation |
|---|---|
| Props-based | Rigid |
| Compound Components | Flexible |
2. How do compound components work internally in React?
โ Answer
They rely on:- Shared state (parent)
- Context API
- Implicit communication
๐ก 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
- Any child can access shared state regardless of depth
๐ด Alternative:
โ Problems:
- Only works for direct children
- Breaks with nesting
๐ก Conclusion:
Context enables true composition flexibility4. 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
- 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
| 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
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 parentTrade-off:
- Flexibility vs independence
12. How do you debug compound component issues in production?
โ Answer
Steps:- Check context provider presence
- Inspect context values
- Verify component hierarchy
- Add runtime validations
๐ก Why:
Most bugs come from incorrect structure13. 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
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 subtree18. 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.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
Edge Cases
- Tabs without panels
- Duplicate IDs
- Dynamic tab addition
๐ช Solution Approach
- Create context for
activeId - Provide setter in parent
- Tabs update state
- 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 navigationConstraints
- Validation before moving forward
Edge Cases
- Skipping steps
- Reset flow
7. ๐ด Menu with Nested Items
๐ Problem
Support deeply nested menusConstraints
- 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 activeEdge 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 managerConstraints
- Add/remove dynamically
Edge Cases
- Auto-dismiss
12. ๐ด Carousel / Slider
๐ Problem
Constraints
- Auto-play
- Swipe support
13. ๐ด Tree View Component
๐ Problem
Nested expandable treeEdge Cases
- Deep recursion
- Performance
14. ๐ด Select / Combobox
๐ Problem
Accessible dropdown with searchConstraints
- 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 contextsConstraints
- Prevent unnecessary re-renders
17. ๐ด Drag-and-Drop List
๐ Problem
Compound draggable listConstraints
- Reordering
18. ๐ด Multi-Select Dropdown
๐ Problem
Select multiple optionsEdge 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 whendefaultId 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?
Missingkey.
๐ก 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
activeIdmanaged 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
- Create context (
activeId,setActiveId) - Implement controlled/uncontrolled logic
- Handle keyboard events
- 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
- Track open state
- Manage focus index
- Handle global events
- 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
- Maintain modal stack
- Render using
ReactDOM.createPortal - 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
- Store form state centrally
- Provide validation API
- 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
- Maintain step index
- Store step metadata
- 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
โ 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
โ 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
โ 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
- 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
โ 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:
- Check context value updates
- Verify provider hierarchy
- Inspect re-renders in DevTools
- 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
โ 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
- 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