Skip to main content

πŸ“˜ 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”
Here, 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
React is fundamentally built around composition rather than inheritance.

πŸ”Ή 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
Instead, React uses:

πŸ”Ή 2.2 The children Prop

At the core of composition is children.
Usage:
πŸ‘‰ Internally:
  • React passes everything inside <Card> as props.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”:
Usage:

πŸ”Ή 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)
  • children becomes part of props
  • During reconciliation:
    • React builds a component tree
    • Each composed component becomes a node
  • React efficiently updates only changed nodes
πŸ‘‰ Composition does NOT create deep inheritance chains β€” just nested trees.

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

πŸ‘‰ Fix:

⚠️ 4.2 Over-Composition

Too many layers:
❌ Leads to:
  • Hard debugging
  • Poor readability

⚠️ 4.3 Prop Drilling Instead of Composition

πŸ‘‰ Instead:
  • Use composition or context

⚠️ 4.4 Misusing Render Props

πŸ‘‰ Should be:

⚠️ 4.5 Breaking Encapsulation

Passing too much control:
❌ Exposes internals

⚠️ 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:
Better:

βœ… 5.4 Avoid Deep Nesting

Flatten when possible:

βœ… 5.5 Combine Composition with Hooks


βœ… 5.6 Memoization for Performance

Use:
  • React.memo
  • useMemo
  • useCallback
When:
  • 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
πŸ‘‰ With composition:
Each component is:
  • 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

  • children is just a prop
  • During JSX transformation:
becomes:
πŸ‘‰ Internally:
  • children is stored inside props.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
πŸ‘‰ With composition:

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

βœ” Flexible ❌ Implicit structure (harder to enforce)

Option 2: Named slots

βœ” Explicit βœ” Easier validation ❌ Slightly verbose

πŸ’‘ 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.
Child components consume it:

πŸ’‘ 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:
βœ” Better:

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

8. How can composition lead to unnecessary re-renders, and how do you prevent it?

βœ… Strong Answer

Problem:
New object every render β†’ re-render

Fix:

Or:

πŸ’‘ 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:
No guarantees of structure.

Solutions:

  1. Runtime validation:
  1. TypeScript constraints
  2. 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
With context:
  • Decoupled data access

13. What are β€œcontrolled vs uncontrolled” composition patterns?

βœ… Strong Answer

Controlled:

Parent controls state

Uncontrolled:

Component manages state

πŸ’‘ Trade-off


14. How do keys affect composed components?

βœ… Strong Answer

Keys affect:
  • Identity
  • Reconciliation

⚠️ Pitfall

Wrong keys:
β†’ causes:
  • State bugs
  • UI mismatches

15. How would you design a flexible layout system using composition?

βœ… Strong Answer

Internally:
  • 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:
  1. Trace props flow
  2. Use React DevTools (component tree)
  3. Check memoization issues
  4. 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:
  • null
  • false
  • undefined
Only valid renderable values like strings, numbers, and JSX are rendered. πŸ‘‰ "Hello" is the only renderable child.

❌ Why others are wrong:

  • A: Incorrect β€” "Hello" is rendered
  • C: React does NOT render null or false
  • 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:
React requires keys for stable reconciliation.

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

β†’ becomes:

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
πŸ‘‰ This leads to state leakage bugs

❌ 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
This is a valid and common pattern.

❌ 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)
No wrapper needed.

❌ Why others are wrong:

  • A: Not required (Fragments exist)
  • B: Cloning is optional
  • C: Arrays are valid

6. What is problematic in this pattern?

Usage:

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:
β†’ TypeError

❌ 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 β†’ breaks React.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?

(with internal context)

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?

(outside <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 a Layout component that supports:
  • Header
  • Sidebar
  • Content
  • Footer
Using composition (not props drilling).

βš™οΈ 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)

  1. Use context to register slots
  2. Identify child types via type
  3. Render in fixed layout positions

🧩 2. Modal with Controlled & Uncontrolled Modes

🧠 Problem

Create a Modal 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 a Form 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:
AND

⚠️ Edge Case

  • Detect if child is function

πŸ’‘ Solution


🧩 8. Card with Strict Child Validation

🧠 Problem

Card should only allow:
  • Card.Header
  • Card.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 render children 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 β†’ breaks React.memo.

βœ… Fix

βœ… Best Practice

Stabilize props in composed trees using useMemo.

🐞 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

Usage:

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

Usage:

πŸ” What’s Wrong

Runtime error.

πŸ’₯ Why It Happens

cloneElement expects single React element, not array.

βœ… Fix

βœ… Best Practice

Always handle multiple children via React.Children.map.

🐞 6. Context Undefined in Compound Component

❌ Buggy Code

Usage:

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

πŸ’₯ 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 original onClick 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 stale count.

πŸ’₯ 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:
    • isOpen
    • activeIndex
    • selectItem

⚠️ Edge Cases

  • Click outside to close
  • Dynamic items list
  • Nested dropdowns

⚑ Performance

  • Avoid re-renders on hover
  • Memoize item list

πŸ— Suggested Architecture


πŸ›  Approach

  1. Create context
  2. Register items dynamically
  3. Handle keyboard events globally
  4. 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

  1. Use createPortal
  2. Manage modal stack
  3. 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

  1. Create field registry
  2. Use context for state
  3. 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 pass isOpen 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 structure

3. 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 of props
  • Converted into fiber nodes
  • Reconciliation depends on:
    • Keys
    • Order
πŸ‘‰ Unstable children β†’ unnecessary re-renders

❌ Weak Answer

β€œChildren is just JSX” πŸ‘‰ Too shallow, no understanding of reconciliation

4. 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

  1. Use React DevTools (highlight updates)
  2. Check prop identity (objects/functions)
  3. Add React.memo
  4. Profile renders

❌ Weak Answer

β€œUse memo everywhere” πŸ‘‰ Blind optimization without root cause analysis

5. 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 scalability

6. 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 experience

7. 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 enforcement

8. Compare composition vs custom hooks for reuse.

πŸ” Follow-ups

  • Can they be combined?

βœ… Strong Answer

  • Composition β†’ UI reuse
  • Hooks β†’ logic reuse
πŸ‘‰ Best systems combine both

❌ Weak Answer

β€œThey are interchangeable” πŸ‘‰ Incorrect mental model

9. 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 incorrect

10. 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 concept

11. 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 limitations

12. 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” πŸ‘‰ Incorrect

13. 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-offs

14. 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 impact

15. How do you design a scalable layout system using composition?

πŸ” Follow-ups

  • Slot-based vs children-based?

βœ… Strong Answer

  • Use slots for clarity:
OR compound pattern

❌ Weak Answer

β€œJust use divs” πŸ‘‰ Not architectural thinking

16. 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 shallow

17. When does composition break encapsulation?

πŸ” Follow-ups

  • How do you fix it?

βœ… Strong Answer

  • Exposing internal state setters
  • Allowing uncontrolled manipulation
πŸ‘‰ Fix via controlled APIs

❌ Weak Answer

β€œIt doesn’t” πŸ‘‰ Incorrect

18. 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” πŸ‘‰ Oversimplified

19. 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/composable

20. 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