Sub topic 9
Composing components into larger interfaces
Composition is how React builds large interfaces: you combine small components, each with one job, into bigger ones. This chapter assumes you can write function components, pass props, and use the children prop. It covers how to split a UI, the common composition patterns, and the mistakes that make composition painful.
What composition means
A component can render other components in its output. A page renders a header and a list. The list renders rows. Each row renders a label and a button. The result is a tree of components, with the root at the top and small leaf components at the bottom.
React favors composition over inheritance. You don't extend one component from another. Instead, a component either renders other components directly, or accepts content from its parent through props and children.
Deciding where to split
There is no fixed rule for component size. These criteria work well in practice:
- One responsibility. If you describe a component and need the word "and" more than once, consider splitting it.
- Repetition. If the same markup appears twice, extract it.
- Distinct data. If a block of UI depends on one clear piece of data, such as a
useror atodo, it often makes a good component. - Readability. If you have to scroll to understand a component, it is probably doing too much.
Don't split too early. A component used once, with no distinct responsibility, may be clearer inline. Extract when the code tells you to, not before.
Pattern 1: Direct nesting with props
The simplest form is a parent that renders children components and passes them data through props.
function Avatar({ user }) {
return <img className="avatar" src={user.imageUrl} alt={user.name} />;
}
function UserName({ user }) {
return <strong>{user.name}</strong>;
}
function UserCard({ user }) {
return (
<div className="user-card">
<Avatar user={user} />
<UserName user={user} />
</div>
);
}
export default function App() {
const user = { name: 'Ada', imageUrl: 'https://example.com/ada.png' };
return <UserCard user={user} />;
}UserCard owns the layout. Avatar and UserName each know how to render one piece. App owns the data and hands it down.
Pattern 2: Containers with children
When a component supplies structure but not content, accept children. The component then works for any content.
function Panel({ title, children }) {
return (
<section className="panel">
<h2>{title}</h2>
<div className="panel-body">{children}</div>
</section>
);
}
export default function App() {
return (
<Panel title="Settings">
<label>
<input type="checkbox" /> Enable notifications
</label>
</Panel>
);
}Panel doesn't know what is inside it. This makes it reusable for settings, profiles, or anything else that needs a titled box. Layout components such as cards, modals, sidebars, and page shells are usually built this way.
Pattern 3: Slots through named props
children is a single slot. When a component needs several regions, pass JSX through other props. A JSX element is an ordinary JavaScript value, so it can be a prop like any other.
function Layout({ header, sidebar, children }) {
return (
<div className="layout">
<header>{header}</header>
<aside>{sidebar}</aside>
<main>{children}</main>
</div>
);
}
export default function App() {
return (
<Layout
header={<h1>Dashboard</h1>}
sidebar={<nav>Links go here</nav>}
>
<p>Main content.</p>
</Layout>
);
}Named slots keep Layout free of knowledge about what the header or sidebar contain. The parent decides.
Pattern 4: Specialization
A specific component can wrap a more general one and fill in some props. This replaces most uses of inheritance.
function Dialog({ title, message, children }) {
return (
<div className="dialog" role="dialog" aria-label={title}>
<h2>{title}</h2>
<p>{message}</p>
{children}
</div>
);
}
function ConfirmDeleteDialog({ itemName, onConfirm }) {
return (
<Dialog
title="Delete item"
message={`Delete "${itemName}"? This cannot be undone.`}
>
<button onClick={onConfirm}>Delete</button>
</Dialog>
);
}ConfirmDeleteDialog is a special case of Dialog. The general component stays simple, and each special case lives in its own small component.
Passing props through layers
When a deep component needs data, the data travels down through every level in between. Each intermediate component must accept and forward it. This is called prop drilling.
function Page({ user }) {
return <Sidebar user={user} />;
}
function Sidebar({ user }) {
return <ProfileLink user={user} />;
}
function ProfileLink({ user }) {
return <a href={`/users/${user.id}`}>{user.name}</a>;
}Here Page and Sidebar carry user only to hand it on. A few layers of this are fine and easy to follow. When it gets long, try these options before reaching for anything heavier:
- Pass only what the child needs, such as
user.nameinstead of the whole object, so components depend on less. - Build the deep element in the parent and pass it down as
childrenor a named prop. The intermediate components then never see the data. - Use context, which lets a component read a value from an ancestor without props at every level. That is a separate topic.
Option 2 is often overlooked. Here is the example rewritten:
function Page({ user }) {
return (
<Sidebar>
<ProfileLink user={user} />
</Sidebar>
);
}
function Sidebar({ children }) {
return <nav className="sidebar">{children}</nav>;
}
function ProfileLink({ user }) {
return <a href={`/users/${user.id}`}>{user.name}</a>;
}Sidebar no longer knows about user. Page renders ProfileLink itself and passes the finished element in.
Choosing a pattern
| Situation | Pattern |
|---|---|
| Parent supplies data to a fixed piece of UI | Direct nesting with props |
| Component provides structure, caller provides content | `children` |
| Component has several content regions | Named props that accept JSX |
| A specific case of a general component | Specialization |
| Intermediate components only forward data | Pass the element down, or use context |
Common errors
Defining components inside components
function Parent({ items }) {
// Wrong: Row is a new function on every render of Parent.
function Row({ item }) {
return <li>{item}</li>;
}
return (
<ul>
{items.map((item) => (
<Row key={item} item={item} />
))}
</ul>
);
}On each render of Parent, Row is a different function. React sees a different component type, so it discards the old subtree and builds a new one. Any local state in the rows is lost. Define Row at the top level of the module instead.
Lowercase component names
React treats <card /> as an HTML element named card, not as your Card component. Component names must start with a capital letter.
Forgetting to render `children`
If a container accepts children but doesn't place {children} in its output, nested content silently disappears. When nested content doesn't show up, check the container first.
Too many props
A component taking fifteen props is often several components in one. If props come in groups, such as userName, userEmail, and userAvatar, pass one user object, or split the component.
Mutating props
Props are read-only. A child must not change an object it received. If a child needs to ask for a change, the parent passes down a function, and the child calls it.
Composing in practice: a small todo list
This example combines the patterns above. App owns the data, TodoList and TodoItem split the rendering, and Section is a reusable container.
import { useState } from 'react';
function Section({ title, children }) {
return (
<section>
<h2>{title}</h2>
{children}
</section>
);
}
function TodoItem({ todo, onToggle }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
{todo.text}
</label>
</li>
);
}
function TodoList({ todos, onToggle }) {
if (todos.length === 0) {
return <p>Nothing to do.</p>;
}
return (
<ul>
{todos.map((todo) => (
<TodoItem key={todo.id} todo={todo} onToggle={onToggle} />
))}
</ul>
);
}
export default function App() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Learn JSX', done: true },
{ id: 2, text: 'Compose components', done: false },
]);
function toggle(id) {
setTodos(
todos.map((todo) =>
todo.id === id ? { ...todo, done: !todo.done } : todo
)
);
}
return (
<Section title="Today">
<TodoList todos={todos} onToggle={toggle} />
</Section>
);
}Data flows down as props, and events flow up as function calls. TodoItem never changes todos. It calls onToggle, and App, which owns the state, makes the update. This one-way flow keeps each component easy to reason about and test on its own.
Exercise
A Modal component takes title and children. A teammate wants to add a footer with action buttons that differ per use. Which change keeps Modal generic, and why?
Show answer
Add a named prop such as footer and render it with {footer} in a footer region of Modal. The caller passes JSX like footer={<button>Save</button>}. Modal never needs to know which buttons exist, so it stays reusable. Adding props like showSaveButton and showCancelButton would force Modal to change for every new use.
Exercise
This component loses the text typed into each input whenever its parent re-renders. What is the cause and the fix? function Form({ fields }) { function Field({ label }) { return <label>{label} <input /></label>; } return fields.map((f) => <Field key={f} label={f} />); }
Show answer
Field is declared inside Form, so each render of Form creates a new function. React treats it as a new component type and remounts every field, which discards the input state. Move Field outside Form to the top level of the module.