Component composition

2 snippets in React

REReact

Component Composition

RE · Components
Syntax
function Parent() {
  return (
    <Layout>
      <Header />
      <Content />
      <Footer />
    </Layout>
  );
}
Example
function PageLayout({ sidebar, content }) {
  return (
    <div className="layout">
      <aside>{sidebar}</aside>
      <main>{content}</main>
    </div>
  );
}

function Dashboard() {
  return (
    <PageLayout
      sidebar={<NavMenu />}
      content={<StatsPanel />}
    />
  );
}

Note Composition via props is preferred over inheritance. Passing components as props gives you flexible "slot" patterns without tightly coupling parent and child.

Prop Drilling Solutions

RE · State Management
Syntax
// 1. Context
// 2. Composition (pass components, not data)
// 3. Component composition with children
Example
// PROBLEM: drilling "user" through many layers
// <App user={user}> -> <Layout user> -> <Header user> -> <Avatar user>

// SOLUTION 1: Context
const UserContext = createContext(null);
// provide at top, consume at Avatar

// SOLUTION 2: Composition -- pass the rendered element
function App({ user }) {
  const avatar = <Avatar user={user} />;
  return <Layout header={<Header avatar={avatar} />} />;
}

// Now Layout and Header don't need to know about "user" at all
function Layout({ header }) {
  return (
    <div>
      <nav>{header}</nav>
      <main>...</main>
    </div>
  );
}

function Header({ avatar }) {
  return <div className="header">{avatar}</div>;
}

Note Before reaching for context, try component composition. Passing pre-rendered elements as props skips intermediate layers entirely and keeps the data flow explicit. Context is better for truly global data (theme, auth, locale).

Frequently asked questions

How does React handle component composition?
React covers this with 2 copy-ready snippets on this page. The "Component Composition" snippet in React uses `function Parent() {`.
Which code does the React example use?
The "Component Composition" snippet uses `function Parent() {`, from the Components section of the React cheat sheet.
What other React snippets are shown for "component composition"?
Besides "Component Composition", this page also shows "Prop Drilling Solutions".
Is there anything to watch out for?
Yes. For "Component Composition": Composition via props is preferred over inheritance. Passing components as props gives you flexible "slot" patterns without tightly coupling parent and child.