๐ Component Composition in React โ Complete Theory Guide
1. Introduction
๐น What is Component Composition?
Component composition is a pattern in React where you build complex UIs by combining smaller, reusable components together. Instead of inheritance, React promotes:๐ โBuild components using other componentsโ
Layout is composed with child elements.
๐น Why is it Important in React?
- Encourages reusability
- Improves maintainability
- Promotes separation of concerns
- Aligns with Reactโs declarative model
๐น When & Why We Use It
Use component composition when:- Building layouts (headers, sidebars, cards)
- Creating reusable UI patterns
- Sharing behavior without inheritance
- Avoiding prop drilling complexity
- Designing flexible APIs for components
2. Concepts / Internal Workings
๐น 2.1 Composition vs Inheritance
React avoids inheritance because:- It creates tight coupling
- Harder to scale and refactor
๐น 2.2 The children Prop
At the core of composition is children.
-
React passes everything inside
<Card>asprops.children -
It can be:
- JSX
- Arrays
- Functions
- Strings
๐น 2.3 Containment Pattern
Used when components act as containers.๐น 2.4 Specialization Pattern
Creating specific components using generic ones.๐น 2.5 Multiple Slots (Advanced Composition)
Sometimes we need multiple โholesโ:๐น 2.6 Function as Children (Render Props)
A powerful composition pattern:๐น 2.7 Compound Components Pattern
Components work together as a group:๐น 2.8 How It Works Internally in React
- JSX is transformed into React elements (objects)
-
childrenbecomes part ofprops -
During reconciliation:
- React builds a component tree
- Each composed component becomes a node
- React efficiently updates only changed nodes
๐น 2.9 Relationship with Other React Features
โ Props
- Composition heavily relies on props (especially
children)
โ State
- State can be lifted or shared across composed components
โ Context API
- Helps avoid prop drilling in deeply composed trees
โ Hooks
- Composition + hooks = reusable logic
3. Syntax & Examples
๐น 3.1 Basic Composition
๐น 3.2 Reusable Card Component
๐น 3.3 Layout Composition
๐น 3.4 Wrapper for Styling
๐น 3.5 Render Props Example
๐น 3.6 Compound Components Example
4. Edge Cases / Common Mistakes
โ ๏ธ 4.1 Forgetting to Render children
โ ๏ธ 4.2 Over-Composition
Too many layers:- Hard debugging
- Poor readability
โ ๏ธ 4.3 Prop Drilling Instead of Composition
- Use composition or context
โ ๏ธ 4.4 Misusing Render Props
โ ๏ธ 4.5 Breaking Encapsulation
Passing too much control:โ ๏ธ 4.6 Key Issues in Composed Lists
5. Best Practices
โ 5.1 Prefer Composition Over Inheritance
- Always favor composition-first design
โ 5.2 Keep Components Small & Focused
Each component should:- Do one thing well
- Be easily composable
โ 5.3 Use Clear Component APIs
Bad:โ 5.4 Avoid Deep Nesting
Flatten when possible:โ 5.5 Combine Composition with Hooks
โ 5.6 Memoization for Performance
Use:React.memouseMemouseCallback
- Components are deeply composed
- Props rarely change
โ 5.7 Use Compound Components for Complex UI
Ideal for:- Tabs
- Accordions
- Dropdowns
โ 5.8 Use Context to Avoid Prop Drilling
โ 5.9 Keep Composition Predictable
- Avoid hidden side effects
- Keep data flow clear
๐ Summary
Component composition is the core philosophy of React:- Build small โ Combine โ Scale
- Prefer flexibility over rigid hierarchies
-
Enables powerful patterns like:
- Render props
- Compound components
- Layout systems
๐ Advanced Interview Questions โ Component Composition (React)
1. What problem does component composition solve that inheritance cannot in React?
โ Strong Answer
Composition solves flexibility and decoupling problems that inheritance introduces.- Inheritance creates tight coupling between parent-child classes
- Leads to rigid hierarchies and difficult refactoring
- React instead uses tree-based composition
- Independent
- Replaceable
- Reusable
๐ก Why this matters
Reactโs reconciliation works on a tree of elements, not class hierarchies. Composition maps naturally to this model.๐ Alternative
- Inheritance โ rigid, static
- Composition โ dynamic, runtime flexibility
2. How does React internally handle children during reconciliation?
โ Strong Answer
childrenis just a prop- During JSX transformation:
childrenis stored insideprops.children- React builds a fiber tree
- Each child becomes a fiber node
๐ก Key Insight
React does not treat children specially after creation โ theyโre just part of the props tree.โ ๏ธ Pitfall
If children change structure:- React diffing depends on keys + order
- Can cause unnecessary re-renders
3. Why is composition preferred over prop drilling for deep component trees?
โ Strong Answer
Prop drilling creates:- Tight coupling across layers
- Hard-to-maintain APIs
- Increased re-render surface
๐ก Why it works
- Data stays closer to where itโs needed
- Intermediate components become agnostic wrappers
๐ Alternative
- Context API for global/shared state
- Composition for structural flexibility
4. What are the trade-offs between children-based composition and explicit props (slots)?
โ Strong Answer
Option 1: children
Option 2: Named slots
๐ก Trade-off Summary
| Approach | Flexibility | Readability | Control |
|---|---|---|---|
| children | High | Medium | Low |
| slots | Medium | High | High |
- API clarity
- Design constraints
5. Explain the Compound Component pattern and its internal coordination mechanism.
โ Strong Answer
Compound components share implicit state via context.๐ก Why this works
- Avoids prop drilling
- Keeps API clean:
โ ๏ธ Trade-off
- Hidden coupling via context
- Harder to debug than explicit props
6. When would you avoid using composition and prefer a custom hook instead?
โ Strong Answer
Use hooks when sharing logic, not UI. โ Composition misuse:๐ก Rule
- Composition โ UI structure
- Hooks โ logic reuse
7. What are the performance implications of deeply composed component trees?
โ Strong Answer
Deep composition can cause:- More fiber nodes
- Increased reconciliation work
- Prop changes cascading downward
Example
๐ก Optimization
React.memo- Avoid unnecessary re-renders
- Stable props with
useCallback
โ ๏ธ Insight
Depth alone isnโt bad โ unstable props are the real issue8. How can composition lead to unnecessary re-renders, and how do you prevent it?
โ Strong Answer
Problem:Fix:
๐ก Core Idea
Composition amplifies prop instability across tree levels.9. What is the difference between render props and component composition?
โ Strong Answer
Render Props
- Dynamic rendering
- Logic-driven composition
Composition
- Static structure
๐ก Trade-off
| Pattern | Flexibility | Complexity |
|---|---|---|
| Composition | Medium | Low |
| Render Props | High | Higher |
10. How do you enforce constraints in a highly composable API?
โ Strong Answer
Problem:Solutions:
- Runtime validation:
- TypeScript constraints
- Compound pattern enforcement
๐ก Trade-off
- Flexibility vs Safety
11. Why can overusing composition hurt readability?
โ Strong Answer
Excess nesting:Issues:
- Hard tracing data flow
- Debug complexity
- Reduced clarity
๐ก Fix
- Flatten structure
- Extract meaningful components
12. How does composition interact with Context API?
โ Strong Answer
Context complements composition:- Composition defines structure
- Context provides data access
๐ก Insight
Without context:- Deep composition โ prop drilling
- Decoupled data access
13. What are โcontrolled vs uncontrolledโ composition patterns?
โ Strong Answer
Controlled:
Uncontrolled:
๐ก Trade-off
| Type | Control | Complexity |
|---|---|---|
| Controlled | High | Higher |
| Uncontrolled | Low | Simpler |
14. How do keys affect composed components?
โ Strong Answer
Keys affect:- Identity
- Reconciliation
โ ๏ธ Pitfall
Wrong keys:- State bugs
- UI mismatches
15. How would you design a flexible layout system using composition?
โ Strong Answer
- Uses context for layout coordination
- Uses slots for flexibility
๐ก Why this design
- Declarative API
- Clear structure
- Scalable
16. When does composition break encapsulation?
โ Strong Answer
If parent controls too much:Problem:
- Leaks internal logic
- Breaks abstraction
๐ก Fix
Expose:- Callbacks
- Controlled APIs
17. How does composition influence testability?
โ Strong Answer
โ Improves testability:- Smaller units
- Easier mocking
โ ๏ธ But:
- Deep composition โ harder integration tests
18. How do you debug issues in a deeply composed component tree?
โ Strong Answer
Approach:- Trace props flow
- Use React DevTools (component tree)
- Check memoization issues
- Inspect re-renders
๐ก Senior Insight
Most bugs come from:- Incorrect assumptions about composition boundaries
- Hidden coupling via context
๐ Final Takeaway
Senior-level understanding of composition means:- Knowing when NOT to use it
- Balancing flexibility vs control
- Understanding how React internally processes trees
- Designing clean, scalable APIs
๐ Advanced MCQs โ Component Composition in React (Senior Level)
1. What will be rendered in this composition scenario?
Options:
A. Nothing renders B. Only"Hello" renders
C. null, false, and "Hello" all render
D. React throws an error
โ Correct Answer: B
โ Explanation:
React ignores:nullfalseundefined
"Hello" is the only renderable child.
โ Why others are wrong:
- A: Incorrect โ
"Hello"is rendered - C: React does NOT render
nullorfalse - D: No error occurs
2. What is the key issue in this composition pattern?
Options:
A. Invalid JSX syntax B. Missing keys in children array C. children cannot be arrays D. Layout must use React.Children.mapโ Correct Answer: B
โ Explanation:
When rendering arrays:โ Why others are wrong:
- A: Syntax is valid
- C: Arrays are allowed
- D: Not required, just optional utility
3. What happens when children change order without keys?
Options:
A. React re-renders both correctly B. React swaps DOM nodes efficiently C. State may get mixed between components D. React throws warning and stops renderingโ Correct Answer: C
โ Explanation:
Without keys:- React uses index-based reconciliation
- Components may retain wrong state
โ Why others are wrong:
- A: Not guaranteed correct
- B: Incorrect โ React cannot track identity
- D: Warning only, not a crash
4. What is the issue with this composition?
Options:
A. Nothing is wrong B. Order of children is not guaranteed C. Card cannot accept multiple children D. Header/Footer must be passed as propsโ Correct Answer: A
โ Explanation:
React preserves:- Order
- Structure of children
โ Why others are wrong:
- B: Order is preserved
- C: Multiple children allowed
- D: Not required
5. What is the subtle bug here?
Options:
A. Wrapper must return a div B. children must be cloned C. Multiple children will cause an error D. Nothing is wrongโ Correct Answer: D
โ Explanation:
React allows returning:- A single child
- Multiple children (as array)
โ Why others are wrong:
- A: Not required (Fragments exist)
- B: Cloning is optional
- C: Arrays are valid
6. What is problematic in this pattern?
Options:
A. Only first child renders B. Runtime error C. Both children render D. Warning onlyโ Correct Answer: B
โ Explanation:
React.Children.only expects exactly one child
Multiple children โ throws error
โ Why others are wrong:
- A: It does not silently ignore
- C: Not allowed
- D: It throws, not warns
7. What happens in this render prop misuse?
Options:
A.<div /> renders normally
B. children is ignored
C. Runtime error
D. โdataโ is rendered
โ Correct Answer: C
โ Explanation:
children is expected to be a function, but itโs a React element.
Calling it:
โ Why others are wrong:
- A: Incorrect type
- B: It is executed, not ignored
- D: Function never runs
8. What is the issue with this composition?
Options:
A. Function will render automatically B. Nothing renders C. React throws error D. Function is converted to stringโ Correct Answer: B
โ Explanation:
React does NOT execute functions passed as children unless explicitly called.โ Why others are wrong:
- A: No automatic execution
- C: No error
- D: Functions are ignored, not stringified
9. Why is this composition inefficient?
Options:
A. config is invalid B. Wrapper causes re-render C. New object each render breaks memoization D. children cannot accept objectsโ Correct Answer: C
โ Explanation:
Every render creates new object โ breaksReact.memo
โ Why others are wrong:
- A: Valid object
- B: Not necessarily
- D: Objects allowed
10. What is the main risk of this compound component pattern?
Options:
A. Performance issues B. Hidden dependency on parent context C. Cannot scale D. JSX limitationโ Correct Answer: B
โ Explanation:
Compound components rely on context โ implicit coupling ๐<Tab> must be inside <Tabs>
โ Why others are wrong:
- A: Not inherently slow
- C: It scales well
- D: No JSX issue
11. What happens if context is missing?
<Tabs>)
Options:
A. Works normally B. Uses default state C. Likely runtime error D. React auto-wrapsโ Correct Answer: C
โ Explanation:
useContext returns undefined โ accessing properties causes error
โ Why others are wrong:
- A: No context โ broken
- B: Only if default defined
- D: React does not auto-wrap
12. What is the issue here?
Options:
A. Invalid syntax B. children prop is overridden C. children cannot be passed explicitly D. Nothing is wrongโ Correct Answer: D
โ Explanation:
children is just a prop โ can be passed explicitly
โ Why others are wrong:
- A: Valid
- B: No override issue
- C: Allowed
13. What is the risk in this pattern?
Options:
A. children cannot be cloned B. Only works with one child C. Breaks React rules D. Causes memory leakโ Correct Answer: B
โ Explanation:
cloneElement requires a single React element
Multiple children โ error
โ Why others are wrong:
- A: It can be cloned
- C: Valid API
- D: No leak
14. What is the issue with deep composition and context?
Options:
A. Context cannot pass deeply B. All components re-render on context change C. Context breaks composition D. Context cannot be nestedโ Correct Answer: B
โ Explanation:
Context updates โ all consumers re-render ๐ Performance concern in large treesโ Why others are wrong:
- A: It can pass deeply
- C: They complement each other
- D: Nesting allowed
15. Why might this API design be problematic?
Options:
A. JSX invalid B. No control over allowed children C. children must be array D. React disallows mixed typesโ Correct Answer: B
โ Explanation:
No constraints โ unpredictable structure ๐ Hard to enforce design rulesโ Why others are wrong:
- A: Valid
- C: Not required
- D: Allowed
16. What happens when returning arrays from children?
Options:
A. Error B. Works if keys exist C. Only first child renders D. Array is flattened automaticallyโ Correct Answer: B
โ Explanation:
React supports arrays, but keys are required for stability.โ Why others are wrong:
- A: No error
- C: All children render
- D: Not โflattenedโ automatically
๐ Final Insight
These questions test whether you understand:- Composition โ just children
-
It deeply affects:
- Reconciliation
- Performance
- API design
- Debugging complexity
๐ Component Composition โ Advanced Coding Problems (React)
These problems simulate real-world UI architecture and design challenges using component composition.๐งฉ 1. Flexible Layout System (Slots-Based)
๐ง Problem
Build aLayout component that supports:
- Header
- Sidebar
- Content
- Footer
โ๏ธ Constraints
- Must allow optional sections
- Order should not matter
- Clean API
โ Expected Usage
โ ๏ธ Edge Cases
- Missing sections
- Multiple headers
- Invalid children
๐ก Solution (Step-by-step)
- Use context to register slots
- Identify child types via
type - Render in fixed layout positions
๐งฉ 2. Modal with Controlled & Uncontrolled Modes
๐ง Problem
Create aModal that supports:
- Controlled (
isOpen) - Uncontrolled (
defaultOpen)
โ๏ธ Constraints
- Must support both modes cleanly
- Avoid duplicate state logic
โ Expected Behavior
- Parent can control open state
- Internal state fallback if not provided
๐ก Solution
๐งฉ 3. Accordion (Compound Components)
๐ง Problem
Build an accordion where items manage open/close via shared state.โ๏ธ Constraints
- Only one item open at a time
- Clean composition API
โ Expected Usage
๐ก Solution
- Use context for active index
- Each item reads & updates it
๐งฉ 4. Tabs with Dynamic Registration
๐ง Problem
Tabs should:- Auto-register children
- Support dynamic addition/removal
โ ๏ธ Edge Cases
- Tabs added after mount
- Missing indices
๐ก Solution Insight
- Use
React.Children.map - Use index-based tracking + keys
๐งฉ 5. Form Builder with Composition
๐ง Problem
Create aForm component where:
- Inputs register themselves
- Form collects values
โ Usage
๐ก Solution
- Context for form state
- Inputs update shared store
๐งฉ 6. Permission-Based Rendering Wrapper
๐ง Problem
Render children only if user has permission.โ๏ธ Constraints
- Should support multiple permissions
- Nested composition
๐ก Solution
๐งฉ 7. Data Fetcher (Render Props vs Composition)
๐ง Problem
Support both:โ ๏ธ Edge Case
- Detect if child is function
๐ก Solution
๐งฉ 8. Card with Strict Child Validation
๐ง Problem
Card should only allow:Card.HeaderCard.Body
โ ๏ธ Edge Cases
- Invalid children
- Multiple headers
๐ก Solution
๐งฉ 9. List Virtualization Wrapper
๐ง Problem
Wrap large lists while preserving composition.โ๏ธ Constraints
- Only render visible items
- Accept child renderer
๐ก Solution
- Use render function
- Combine with windowing logic
๐งฉ 10. Theme Provider with Composition
๐ง Problem
Provide theme to deeply nested components.๐ก Solution
๐งฉ 11. Tooltip Wrapper (Composition Control)
๐ง Problem
Wrap any element with tooltip behavior.โ ๏ธ Edge Case
- Child must accept props
๐ก Solution
๐งฉ 12. Error Boundary Wrapper
๐ง Problem
Catch errors in composed children.๐ก Solution
- Use class component
- Wrap children
๐งฉ 13. Multi-Step Form Wizard
๐ง Problem
Steps defined via composition:๐ก Solution
- Track active step via context
- Render one step at a time
๐งฉ 14. Portal-Based Modal System
๐ง Problem
Render children outside DOM hierarchy.๐ก Solution
๐งฉ 15. Drag-and-Drop Wrapper
๐ง Problem
Enable drag behavior for any child.โ ๏ธ Edge Case
- Child event conflicts
๐ก Solution
- Inject handlers via cloning
๐งฉ 16. Layout Switcher (Responsive Composition)
๐ง Problem
Switch layout based on screen size.๐ก Solution
- Conditional composition
๐งฉ 17. Notification System (Stacked Composition)
๐ง Problem
Allow multiple notifications via composition.๐ก Solution
- Context store + dynamic children
๐งฉ 18. Skeleton Loader Wrapper
๐ง Problem
Wrap content with loading placeholder.๐ก Solution
๐งฉ 19. Access-Controlled Route Wrapper
๐ง Problem
Restrict route access via composition.๐ก Solution
๐งฉ 20. Analytics Wrapper (Cross-Cutting Concern)
๐ง Problem
Track interactions across children.๐ก Solution
- Wrap children
- Inject tracking props/events
๐ Final Takeaway
These problems test your ability to:- Design scalable APIs
- Balance flexibility vs control
- Handle real-world constraints
- Understand composition deeply (not just children)
๐ Component Composition โ Real-World Debugging Challenges (Senior Code Review)
These are production-grade bugs involving composition, not trivial mistakes.๐ 1. Children Not Rendering
โ Buggy Code
๐ Whatโs Wrong
children is never rendered.
๐ฅ Why It Happens
In composition, children are just props โ React wonโt render them automatically.โ Fix
โ Best Practice
Always explicitly renderchildren in container components.
๐ 2. Broken Memoization Due to Inline Composition
โ Buggy Code
๐ Whatโs Wrong
Child re-renders every time.๐ฅ Why It Happens
New object reference on each render โ breaksReact.memo.
โ Fix
โ Best Practice
Stabilize props in composed trees usinguseMemo.
๐ 3. State Leakage Due to Missing Keys
โ Buggy Code
๐ Whatโs Wrong
Inputs show incorrect values after reordering.๐ฅ Why It Happens
Index-based keys โ React reuses wrong components.โ Fix
โ Best Practice
Never use index as key in dynamic composed lists.๐ 4. Render Prop Misuse
โ Buggy Code
๐ Whatโs Wrong
Function never executes.๐ฅ Why It Happens
React does not auto-call function children.โ Fix
โ Best Practice
Detect and handle function-as-children explicitly.๐ 5. CloneElement Crash with Multiple Children
โ Buggy Code
๐ Whatโs Wrong
Runtime error.๐ฅ Why It Happens
cloneElement expects single React element, not array.
โ Fix
โ Best Practice
Always handle multiple children viaReact.Children.map.
๐ 6. Context Undefined in Compound Component
โ Buggy Code
๐ Whatโs Wrong
App crashes.๐ฅ Why It Happens
No provider โuseContext returns undefined.
โ Fix
โ Best Practice
Guard compound components against missing providers.๐ 7. Hidden Re-render Cascade
โ Buggy Code
๐ Whatโs Wrong
Child re-renders even if it doesnโt usecount.
๐ฅ Why It Happens
Parent re-render โ all children re-render.โ Fix
โ Best Practice
Memoize deeply composed children.๐ 8. Incorrect Child Type Assumption
โ Buggy Code
๐ Whatโs Wrong
Crashes when child is string/null.๐ฅ Why It Happens
Children can be:- strings
- null
- arrays
โ Fix
โ Best Practice
Always validate children before accessing props.๐ 9. Function Child Not Called Conditionally
โ Buggy Code
๐ Whatโs Wrong
Crashes if children is not function.๐ฅ Why It Happens
Assumes children is callable.โ Fix
โ Best Practice
Support both patterns safely.๐ 10. Overwriting Event Handlers
โ Buggy Code
๐ Whatโs Wrong
Childโs originalonClick lost.
๐ฅ Why It Happens
Props are overwritten.โ Fix
โ Best Practice
Merge, donโt override props.๐ 11. Multiple Slot Collision
โ Buggy Code
๐ Whatโs Wrong
Only last child kept.๐ฅ Why It Happens
Same key overwritten.โ Fix
โ Best Practice
Handle multiple instances safely.๐ 12. Stale Closure in Composed Callback
โ Buggy Code
๐ Whatโs Wrong
May use stalecount.
๐ฅ Why It Happens
Closure captures old state.โ Fix
โ Best Practice
Use functional updates in composed callbacks.๐ 13. Fragment Children Misinterpretation
โ Buggy Code
๐ Whatโs Wrong
Fails for fragments.๐ฅ Why It Happens
Fragments wrap multiple children but count as one.โ Fix
โ Best Practice
Normalize children before inspection.๐ 14. Conditional Rendering Losing State
โ Buggy Code
๐ Whatโs Wrong
Child state resets when toggled.๐ฅ Why It Happens
Component unmounts/remounts.โ Fix
โ Best Practice
Avoid unmounting when state must persist.๐ 15. Deep Composition Causing Prop Drilling
โ Buggy Code
๐ Whatโs Wrong
Unnecessary prop passing.๐ฅ Why It Happens
Poor composition design.โ Fix
Use context:โ Best Practice
Use context for deeply shared data.๐ 16. Unstable Child Identity
โ Buggy Code
๐ Whatโs Wrong
New function every render โ re-renders.๐ฅ Why It Happens
Function identity changes.โ Fix
โ Best Practice
Stabilize function props.๐ 17. Unexpected Rendering Order
โ Buggy Code
๐ Whatโs Wrong
Keys shift โ order instability.๐ฅ Why It Happens
Filtering without preserving keys.โ Fix
โ Best Practice
Normalize + filter safely.๐ 18. Infinite Re-render Loop via Composition
โ Buggy Code
๐ Whatโs Wrong
Child triggers update โ infinite loop.๐ฅ Why It Happens
Unstable callback causes repeated updates.โ Fix
โ Best Practice
Stabilize callbacks passed through composition.๐ Final Takeaway
Real-world composition bugs usually come from:- โ Wrong assumptions about
children - โ Unstable references (objects/functions)
- โ Hidden coupling (context, compound patterns)
- โ Misuse of React utilities (
cloneElement,Children) - โ Reconciliation misunderstandings
๐ Component Composition โ Real-World Machine Coding Problems (Senior Architect Level)
These problems simulate production-grade frontend architecture challenges where component composition is central.๐งฉ 1. Headless Dropdown System (Composable API)
๐ง Problem
Build a fully accessible dropdown system with:- Trigger
- Menu
- Items
โ Requirements
- Keyboard navigation (โ โ Enter Esc)
- Controlled + uncontrolled modes
- Custom rendering of items
๐ฏ UI Behavior
- Clicking trigger toggles menu
- Arrow keys navigate items
- Only one item active
๐ State/Data Flow
-
Shared via context:
isOpenactiveIndexselectItem
โ ๏ธ Edge Cases
- Click outside to close
- Dynamic items list
- Nested dropdowns
โก Performance
- Avoid re-renders on hover
- Memoize item list
๐ Suggested Architecture
๐ Approach
- Create context
- Register items dynamically
- Handle keyboard events globally
- Use refs for focus control
๐งฉ 2. Headless Modal System with Portal
๐ง Problem
Create a composable modal system supporting:- Multiple modals
- Nested modals
- Portal rendering
๐ฏ UI Behavior
- Modal overlays page
- Focus trapped inside
- Escape closes modal
๐ Data Flow
- Global modal manager (context/store)
โ ๏ธ Edge Cases
- Multiple modals stacked
- Background scroll lock
โก Performance
- Avoid re-rendering entire app
- Use portals for isolation
๐ Architecture
๐ Approach
- Use
createPortal - Manage modal stack
- Trap focus with refs
๐งฉ 3. Dynamic Form Builder (Schema + Composition)
๐ง Problem
Build a form system where:- Fields self-register
- Supports validation & dynamic fields
๐ฏ UI Behavior
- Real-time validation
- Dynamic addition/removal of fields
๐ Data Flow
- Central form state via context
โ ๏ธ Edge Cases
- Nested fields
- Async validation
โก Performance
- Avoid re-rendering entire form
- Field-level subscriptions
๐ Architecture
๐ Approach
- Create field registry
- Use context for state
- Isolate updates per field
๐งฉ 4. Compound Tabs with Lazy Rendering
๐ง Problem
Tabs where inactive panels are not rendered.โ ๏ธ Edge Cases
- Preserving state on unmount
- Dynamic tab addition
โก Performance
- Lazy mount panels
- Memoize tab content
๐ Architecture
๐ Approach
- Track active tab
- Conditionally render panel
๐งฉ 5. Notification System (Global + Composable)
๐ง Problem
Create a toast system with:- Stacked notifications
- Auto-dismiss
- Custom content
๐ Data Flow
- Global context store
โ ๏ธ Edge Cases
- Rapid fire notifications
- Duplicate messages
โก Performance
- Avoid re-rendering all toasts
๐ Architecture
๐ Approach
- Maintain queue
- Render via portal
๐งฉ 6. Drag-and-Drop Composable System
๐ง Problem
Enable drag-drop via composition.โ ๏ธ Edge Cases
- Nested draggables
- Performance on large lists
โก Performance
- Avoid full re-renders during drag
๐ Architecture
๐ Approach
- Inject props via cloneElement
- Use refs for DOM tracking
๐งฉ 7. Virtualized List with Render Composition
๐ง Problem
Render large datasets efficiently.โ ๏ธ Edge Cases
- Dynamic item heights
- Scroll jumps
โก Performance
- Windowing
- Memoized item renderer
๐ Architecture
๐ Approach
- Calculate visible range
- Render subset
๐งฉ 8. Multi-Step Wizard
๐ง Problem
Composable steps with shared state.โ ๏ธ Edge Cases
- Skippable steps
- Async validation
๐ Architecture
๐ Approach
- Track current step
- Share state via context
๐งฉ 9. Access-Control Wrapper System
๐ง Problem
Control UI visibility based on roles.โ ๏ธ Edge Cases
- Nested permissions
- Async auth
๐ Architecture
๐ Approach
- Context-based auth
- Conditional rendering
๐งฉ 10. Analytics Wrapper
๐ง Problem
Track user interactions across app.โ ๏ธ Edge Cases
- Prevent duplicate tracking
- Debounce events
๐ Architecture
๐ Approach
- Inject handlers via cloning
- Central tracking system
๐งฉ 11. Layout System with Responsive Composition
๐ง Problem
Switch layout dynamically.โ ๏ธ Edge Cases
- Resize events
- SSR mismatch
๐ Architecture
๐ Approach
- Media queries + composition switching
๐งฉ 12. Skeleton Loader Wrapper
๐ง Problem
Wrap any component with loading state.โ ๏ธ Edge Cases
- Partial loading
- Layout shifts
๐ Approach
- Conditional rendering + placeholder
๐งฉ 13. Infinite Scroll Feed
๐ง Problem
Composable feed with lazy loading.โ ๏ธ Edge Cases
- Scroll threshold issues
- Duplicate fetches
๐ Approach
- IntersectionObserver
- State batching
๐งฉ 14. Global Search Overlay
๐ง Problem
Search UI accessible anywhere.โ ๏ธ Edge Cases
- Keyboard shortcut conflicts
- Debounce search
๐ Approach
- Portal + context
๐งฉ 15. Table System (Headless + Composable)
๐ง Problem
Customizable table:- Columns
- Sorting
- Pagination
โ ๏ธ Edge Cases
- Large datasets
- Column reordering
๐ Approach
- Headless logic + UI composition
๐งฉ 16. Feature Flag Wrapper
๐ง Problem
Enable/disable features dynamically.โ ๏ธ Edge Cases
- Async flags
- A/B testing
๐ Approach
- Context-based flags
๐งฉ 17. Error Boundary System (Composable)
๐ง Problem
Wrap parts of app for error isolation.โ ๏ธ Edge Cases
- Nested boundaries
- Reset behavior
๐ Approach
- Class-based error boundaries
๐งฉ 18. Command Palette (Keyboard Driven UI)
๐ง Problem
Global command system (like VS Code).โ ๏ธ Edge Cases
- Focus management
- Search ranking
๐ Approach
- Context + portal + keyboard events
๐งฉ 19. Timeline/Activity Feed System
๐ง Problem
Composable event feed with grouping.โ ๏ธ Edge Cases
- Time grouping
- Dynamic updates
๐ Approach
- Data transformation + composed UI
๐งฉ 20. Nested Menu System
๐ง Problem
Multi-level navigation menus.โ ๏ธ Edge Cases
- Keyboard navigation
- Deep nesting
๐ Approach
- Recursive composition
- Context for active state
๐ Final Takeaway
These problems test true senior-level skills:- Designing composable APIs
- Managing state across trees
- Handling performance + edge cases
- Balancing flexibility vs control
๐ FAANG-Level Interview Questions โ Component Composition (React)
These questions probe architecture thinking, trade-offs, debugging ability, and performance awareness โ not surface knowledge.1. Design a flexible Modal API using composition. What trade-offs would you consider?
๐ Follow-ups
- How would you support nested modals?
- How would you prevent misuse of subcomponents?
โ Strong Answer
- Use compound components:
- Share state via context
- Use portal for rendering
- Add guards for invalid usage
๐ก Trade-offs
- Flexibility vs API constraints
- Context coupling vs explicit props
โ Weak Answer
โJust passisOpen prop and render childrenโ
๐ Fails because:
- Ignores composability
- Doesnโt scale for complex UI
2. When would you prefer render props over composition?
๐ Follow-ups
- What are performance implications?
- How does it affect readability?
โ Strong Answer
-
Use render props when:
- UI depends on dynamic data/logic
- Need runtime control
๐ก Trade-off
- More flexible but harder to read/debug
โ Weak Answer
โRender props are just another way to pass childrenโ ๐ Misses key difference: function execution vs static structure3. How does React treat children internally, and why does it matter for performance?
๐ Follow-ups
- How does reconciliation use keys?
- What happens with unstable children?
โ Strong Answer
-
childrenโ part ofprops - Converted into fiber nodes
-
Reconciliation depends on:
- Keys
- Order
โ Weak Answer
โChildren is just JSXโ ๐ Too shallow, no understanding of reconciliation4. You see unnecessary re-renders in a deeply composed tree. How do you debug?
๐ Follow-ups
- What tools would you use?
- How do you isolate the issue?
โ Strong Answer
- Use React DevTools (highlight updates)
- Check prop identity (objects/functions)
- Add
React.memo - Profile renders
โ Weak Answer
โUse memo everywhereโ ๐ Blind optimization without root cause analysis5. Design a Tabs system using composition. How do you handle state sharing?
๐ Follow-ups
- What if tabs are dynamically added?
- How do you prevent misuse?
โ Strong Answer
- Compound components + context
- Track active index
- Register children dynamically
โ Weak Answer
โPass active tab as prop to each Tabโ ๐ Leads to prop drilling and poor scalability6. What are the risks of overusing composition?
๐ Follow-ups
- When does composition hurt readability?
- How do you balance abstraction?
โ Strong Answer
- Deep nesting โ hard debugging
- Implicit structure โ unclear APIs
- Hidden coupling via context
โ Weak Answer
โNo downsides, composition is always goodโ ๐ Shows lack of real-world experience7. How do you enforce constraints in a composable API?
๐ Follow-ups
- Compile-time vs runtime validation?
โ Strong Answer
-
Use:
- TypeScript typings
- Runtime validation (
child.type) - Controlled compound components
โ Weak Answer
โDocument itโ ๐ Documentation is not enforcement8. Compare composition vs custom hooks for reuse.
๐ Follow-ups
- Can they be combined?
โ Strong Answer
- Composition โ UI reuse
- Hooks โ logic reuse
โ Weak Answer
โThey are interchangeableโ ๐ Incorrect mental model9. How does composition impact bundle size and performance?
๐ Follow-ups
- Tree-shaking implications?
โ Strong Answer
- More components โ worse performance
-
But:
- More layers โ more renders
- Inline functions/objects hurt memoization
โ Weak Answer
โMore components always slowerโ ๐ Oversimplified and incorrect10. How would you design a headless UI component system?
๐ Follow-ups
- How do you separate logic from UI?
โ Strong Answer
- Provide logic via hooks/context
- Let consumers compose UI
โ Weak Answer
โJust style componentsโ ๐ Misses headless concept11. What issues arise with React.cloneElement in composition?
๐ Follow-ups
- Alternatives?
โ Strong Answer
- Only works with single child
- Overrides props unintentionally
- Breaks ref forwarding
โ Weak Answer
โItโs fine to use everywhereโ ๐ Ignores limitations12. How do keys affect composed components beyond lists?
๐ Follow-ups
- Can keys reset state?
โ Strong Answer
- Keys control identity
- Changing key โ remount โ state reset
โ Weak Answer
โKeys are only for listsโ ๐ Incorrect13. Design a system to avoid prop drilling in deep composition.
๐ Follow-ups
- When NOT to use context?
โ Strong Answer
- Use context for shared data
- Avoid overusing context (performance issues)
โ Weak Answer
โAlways use contextโ ๐ Ignores trade-offs14. What is a subtle bug when using function-as-children?
๐ Follow-ups
- Performance implications?
โ Strong Answer
- Function recreated each render
- Causes re-renders if not memoized
โ Weak Answer
โNo issuesโ ๐ Misses real-world impact15. How do you design a scalable layout system using composition?
๐ Follow-ups
- Slot-based vs children-based?
โ Strong Answer
- Use slots for clarity:
โ Weak Answer
โJust use divsโ ๐ Not architectural thinking16. How would you debug a broken compound component system?
๐ Follow-ups
- What if context is undefined?
โ Strong Answer
- Check provider presence
- Validate usage
- Add error boundaries
โ Weak Answer
โCheck console logsโ ๐ Too shallow17. When does composition break encapsulation?
๐ Follow-ups
- How do you fix it?
โ Strong Answer
- Exposing internal state setters
- Allowing uncontrolled manipulation
โ Weak Answer
โIt doesnโtโ ๐ Incorrect18. How does composition interact with Suspense and lazy loading?
๐ Follow-ups
- Where do you place boundaries?
โ Strong Answer
- Wrap composed parts with Suspense
- Lazy load heavy children
โ Weak Answer
โSuspense handles everythingโ ๐ Oversimplified19. Design a reusable analytics wrapper using composition.
๐ Follow-ups
- Avoid double tracking?
โ Strong Answer
- Wrap children
- Inject event handlers carefully
- Deduplicate events
โ Weak Answer
โLog inside componentโ ๐ Not reusable/composable20. What is the hardest part of designing composable systems at scale?
๐ Follow-ups
- How do you measure success?
โ Strong Answer
-
Balancing:
- Flexibility
- Constraints
- Performance
- Avoiding hidden coupling
โ Weak Answer
โJust reuse componentsโ ๐ Misses system design depth๐ Final Insight
A strong candidate demonstrates:- Deep understanding of React internals
- Ability to reason about trade-offs
- Awareness of performance & debugging
- Skill in designing clean, scalable APIs