π 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
π Senior engineers choose based on:
- 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
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
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