ReactEasy

What is component composition?

Component composition is building complex UIs by combining smaller components, passing components and JSX into each other through children and other props, instead of inheritance or giant configurable components. It is React's main mechanism for reuse and for avoiding prop drilling.

Techniques

  • Nesting: <Page><Header /><Content /></Page>.
  • Children: a Card renders whatever it wraps.
  • Slots: named JSX props such as header, sidebar, actions.
  • Specialization: DangerButton renders <Button variant="danger" {...props} />.
  • Compound components: <Tabs><Tabs.List /><Tabs.Panel /></Tabs> sharing state through context.
  • Render props or function children: a component calls a function to let the caller decide what to render.
  • Hooks for logic: custom hooks share behavior; components share UI.

Composition vs inheritance

React's docs have always recommended composition; component inheritance hierarchies are almost never needed.

Composition fixes prop drilling

If App has user and only Avatar deep inside needs it, App can create <Avatar user={user} /> and pass it as a slot to Layout. Intermediate components never see user.

Performance bonus

Elements passed as children are created by the parent. When the wrapping component re-renders because of its own state, those children do not re-render, since their element objects are unchanged.

Code example

tsx
1import { useState } from "react";
2
3function Layout({ header, sidebar, children }: { header: React.ReactNode; sidebar: React.ReactNode; children: React.ReactNode }) {
4 return (
5 <div className="grid grid-cols-[200px_1fr]">
6 <header className="col-span-2">{header}</header>
7 <aside>{sidebar}</aside>
8 <main>{children}</main>
9 </div>
10 );
11}
12
13function Collapsible({ children }: { children: React.ReactNode }) {
14 const [open, setOpen] = useState(true);
15 // `children` does not re-render when `open` changes: the parent created it
16 return (
17 <section>
18 <button onClick={() => setOpen((o) => !o)}>{open ? "Hide" : "Show"}</button>
19 {open && children}
20 </section>
21 );
22}
23
24export function App({ user }: { user: { name: string } }) {
25 return (
26 <Layout header={<h1>Hi {user.name}</h1>} sidebar={<nav>Menu</nav>}>
27 <Collapsible>
28 <p>Composed content</p>
29 </Collapsible>
30 </Layout>
31 );
32}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app