π 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
π 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)
- 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:
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
π‘ 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
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