Sub topic 1
Composition and the children prop
React components are functions, so you combine them by nesting. This chapter covers the children prop, the main tool for that. The later chapters (compound components, render props, control props) all build on it.
Prerequisites
This chapter assumes you can:
- Write function components and JSX, and pass props.
- Use
useStateand handle events such asonClick. - Pass functions as props.
- Read ES module imports and exports, and use destructuring.
You do not need context, custom hooks, or any pattern from the later chapters.
What composition means
Composition means building a component from other components. The parent decides what goes inside the child, and the child decides how to present it. React recommends composition over inheritance. Component classes that extend other component classes are rare in React code, because props and nesting cover almost every reuse case.
There are two common forms:
- Containment: a component does not know its content ahead of time and renders whatever it is given.
- Specialization: a component is a more specific version of a general one and renders it with fixed props.
The children prop
Everything you place between a component's opening and closing tags arrives as props.children.
function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}
export function Profile() {
return (
<Card title="Profile">
<p>Ada Lovelace</p>
<button>Follow</button>
</Card>
);
}Card controls the frame: the section, the heading, and the class name. Profile controls the content. Card needs no props like body or actions, and it never needs to change when the content does.
Specialization
A specialized component wraps a general one and fixes some props. It passes children through unchanged.
function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}
export function ErrorCard({ children }) {
return (
<Card title="Something went wrong">
<div role="alert">{children}</div>
</Card>
);
}ErrorCard adds an alert role around its content. Callers write <ErrorCard>Network lost</ErrorCard> and get the frame and the semantics without repeating them.
What children can be
children is not always an array of elements. Its shape depends on what the caller wrote:
| Caller writes | `children` is |
|---|---|
| Nothing between the tags | `undefined` |
| Text only | a string |
| One element | a single element object, not an array |
| Several elements | an array |
| An expression like `{cond && <A />}` | `false`, `null`, or an element |
| A function | a function (used by render props, covered later) |
Two consequences follow:
- Rendering
{children}is always safe, because React skipsundefined,null, and booleans. - Calling
children.maporchildren.lengthdirectly is a bug. It crashes with a single child and gives wrong results with a string.
When you must inspect or transform children, use the Children helpers.
import { Children } from 'react';
export function List({ children }) {
const items = Children.toArray(children);
return (
<ul>
{items.map((child, index) => (
<li key={child.key ?? index}>{child}</li>
))}
</ul>
);
}Children.toArray flattens nested arrays, removes null, undefined, and booleans, and assigns stable keys to elements. Strings and numbers have no key property, so the fallback to index is needed.
Composition and rendering cost
Composition has a performance benefit. When a component renders children that its own parent created, React can skip them when only the wrapper's state changes.
import { useState } from 'react';
function ExpensiveTree() {
console.log('ExpensiveTree rendered');
return <p>Static content</p>;
}
function MouseTracker({ children }) {
const [x, setX] = useState(0);
return (
<div onMouseMove={(event) => setX(event.clientX)}>
<p>x: {x}</p>
{children}
</div>
);
}
export function App() {
return (
<MouseTracker>
<ExpensiveTree />
</MouseTracker>
);
}App creates the <ExpensiveTree /> element once. When MouseTracker updates its state, it re-renders, but children is the same element object as before. React sees the same element and skips rendering it. If ExpensiveTree were written directly inside MouseTracker, it would re-render on every mouse move.
This only holds while the parent that creates the children does not re-render. If App re-renders, it builds a new element and ExpensiveTree renders again.
Avoiding prop drilling with composition
Prop drilling means passing a prop through several components that do not use it. Composition often removes the need.
Suppose Page receives a user only to hand it to Header, which hands it to Avatar. Instead, let the top component build the leaf and pass it down as children or as a prop.
function Avatar({ name }) {
return <img alt={name} src={`/avatars/${name}.png`} />;
}
function Header({ children }) {
return <header>{children}</header>;
}
function Page({ header, children }) {
return (
<div>
{header}
<main>{children}</main>
</div>
);
}
export function App({ user }) {
return (
<Page header={<Header><Avatar name={user.name} /></Header>}>
<p>Welcome back.</p>
</Page>
);
}Page and Header know nothing about user. Only App does. Passing elements as named props such as header is the idea behind the slots pattern, which has its own chapter.
Common errors
- Defining components inside another component's body. The inner function is a new component type on every render, so React unmounts and remounts it and loses its state. Define components at module level.
- Treating
childrenas an array. See the table above. UseChildren.toArrayorChildren.count. - Cloning children to inject props.
cloneElementbreaks when a child is wrapped by another component, because the injected props go to the wrapper. Prefer context. - Creating new elements for children on every render and expecting memoization to work.
React.memoon a child that receiveschildrenalways re-renders when the parent re-creates the elements, because each render produces a new object. - Forgetting to render
children. A wrapper that destructureschildrenbut never outputs it silently drops the content, with no error.
Why this matters for the rest of the tutorial
Compound components work by letting the consumer write the structure as children while the parent shares state behind the scenes. You can only do that if you already treat children as the place where the caller's structure goes. Lifting state, render props, and the other patterns that follow all assume this step.
Exercise
A Panel component renders <div className="panel">{children.map(c => <div>{c}</div>)}</div>. It works with two child elements but crashes with one. Why, and how do you fix it?
Show answer
With one child element, children is a single element object, not an array, so children.map does not exist. With text only it would be a string. Fix it by using Children.map(children, c => <div>{c}</div>) or Children.toArray(children).map(...), both of which accept any shape of children. If you do not need to wrap each child, simply render {children}.
Exercise
Layout re-renders every time its sidebarOpen state changes. You render <ExpensiveChart /> inside Layout's own JSX, and it re-renders each time too. How can you stop the chart from re-rendering without React.memo?
Show answer
Move the <ExpensiveChart /> element to the parent of Layout and pass it as children (<Layout><ExpensiveChart /></Layout>). The parent creates the element once, so when Layout re-renders because of its own state, children is the same element and React skips it. This works only while the parent itself does not re-render.