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