Course contentsShow
← React
Lesson 2325 of 2,39650. Performance: Optimization TechniquesFree lesson

Composition Over Context

Passing components as children or props to avoid wrapping everything in context when simple composition works.

Composition Over Context

What you'll learn: How to avoid unnecessary context wrappers by passing components as children or props—a simpler, faster alternative when data doesn't need to tunnel through many layers.

The Core Idea

Sometimes we reach for Context when we just need to pass a component down the tree. Instead of wrapping everything in a Provider and making dozens of components "listen" for changes, you can pass the component itself as a children prop or explicit prop. The parent renders it wherever needed—no context, no re-renders for unrelated consumers.

Think of it like handing someone a pre-wrapped gift instead of giving them instructions to build it themselves. The component is already constructed; you're just deciding where to place it.

Why This Matters

Context makes every consumer re-render when the value changes. If you only need to insert a component into a specific slot (like a sidebar, header, or modal), composition lets you build it once in the parent and pass it down. The parent controls what gets rendered, but child components don't re-render unnecessarily.

The Pattern

// Instead of wrapping everything in UserContext:
function Layout({ sidebar, content }) {
  return (
    <div className="layout">
      <aside>{sidebar}</aside>
      <main>{content}</main>
    </div>
  );
}

// Parent composes:
<Layout 
  sidebar={<UserProfile user={currentUser} />}
  content={<Dashboard />}
/>

The Layout component doesn't know or care about user. It just places the pre-built sidebar where it belongs. No context needed.

When to Use This

If the data lives close to where the component is created, and you're just deciding placement, composition wins. Save context for truly global state that many distant components need to access independently.

Key Takeaway: Before adding context, ask if you can just pass the component itself as a prop—composition eliminates context overhead when you only need structural flexibility, not data tunneling.