What you'll learn: By the end of this lesson you will be able to cut a page into a tree of components that match its data, say what a component owns (its props, its state, nothing else), decide which data is state and which is derived, lift state to the closest common parent, split a stateful container from a presentational view, tell controlled from uncontrolled components, and spot the classic failure of defining one component inside another.
Think of a restaurant kitchen at the dinner rush. Each station has one job: grill, salads, desserts. A station takes tickets in, hands plates out, and does not walk into another station to grab ingredients. The head chef owns the order list and decides who gets which ticket. If the kitchen is organised this way, you can replace the salad cook without touching the grill, and you can test the dessert station by handing it a fake ticket.
A component-based front end works the same way: a tree of small units, each receiving what it needs and reporting what happened. This lesson is about where to draw those lines and who owns what.
The running example is the product browser on the ShopStream grocery marketplace: a search box, a product list with an Add button on each row, and a cart summary.
The core idea
- A component is a unit with a narrow job. React's documentation describes components as reusable UI elements, written as JavaScript functions that you sprinkle with markup, and says you can compose, order and nest them to design whole pages.
- Data flows down as props, and events flow up as callbacks. A child never reaches into its parent's state. It reads props and calls the functions it was given.
- Every piece of state has exactly one owner. React calls this a "single source of truth". The owner is the closest component above everyone who needs the data.
Three illustrations run through the lesson: a minimal example (one row tested with props alone), a realistic example (the whole product browser) and a failure example (a component defined inside another).
This lesson is about where the boundaries go. The next one, component composition and API design, is about what a boundary looks like (slots, compound components, render props).
What a component is, and is not
React components are regular functions whose names start with a capital letter, and they return markup. Two rules shape everything that follows.
- Props are the only argument, and they are read-only. When something must change, you "set state" in the component that owns it.
- Rendering is pure. The same inputs must give the same markup, and a component must not change objects that existed before it was called. See purity, Strict Mode and refs.
The rest of the architecture is about choosing which inputs each function gets.
Illustration 1: the minimal example
The smallest useful component in the lab reads everything from props and reports everything through a callback. This excerpt is from the lab's presentational.tsx:
export function ProductRow({ product, onAdd }: { product: Product; onAdd: (id: string) => void }) {
return (
<li>
<span>{product.name}</span> <span>{formatPrice(product.priceCents)}</span>
{product.inStock ? null : <span> Out of stock</span>}
<button type="button" disabled={!product.inStock} onClick={() => onAdd(product.id)}>
{`Add ${product.name} to cart`}
</button>
</li>
);
}
To test it you need no server and no provider: render it with a product and a spy, click, and check the spy was called with "milk". A second lab test shows an out-of-stock product gets a disabled button, so the callback is never reached. A narrow component has a test as small as its job.
Cutting a page into a tree
"Thinking in React" starts from the data. Well-structured data often maps naturally to the component structure, because UI and data models tend to have the same shape, so each component matches one piece of the data model. Its test for size: a component should ideally be concerned with one thing, and if it grows, decompose it.
For the product browser the data model is a list of products, a search text and a cart. The lab's types mirror that (Product, Cart, LoadStatus).
Figure 1. The product browser as a component tree
How to read this: the container is the only box that owns state or talks to the outside. Everything to its right is a function of props, so each box can be rendered and tested alone.
A component tree is not a folder tree: this is the runtime shape, which component renders which. File placement is in feature-based folder structure.
Where state lives
"Thinking in React" defines state as the minimal set of changing data an app needs to remember, and gives three tests for data that is not state: it never changes, it comes from a parent as props, or you can compute it from existing state or props. The state-structure guide adds that calculable information should not go into state.
Apply that to the product browser. The visible list is the filter of the loaded products by the search text, so it is derived. The cart count and total are computed from the cart and the products, so they are derived. What remains as state: the load status, the loaded products, the search text, the cart and a retry counter. The lab's hook owns those five and derives the rest during render.
return {
status,
query,
visibleProducts: filterProducts(products, query),
cartCount: cartCount(cart),
cartTotalCents: cartTotalCents(cart, products),
onQueryChange: setQuery,
onAdd: (id: string) => setCart((current) => ({ ...current, [id]: (current[id] ?? 0) + 1 })),
// ... onRetry and onClearCart are one-line setters like these
};
Three returned values come from plain functions with no React in them (filterProducts, cartCount, cartTotalCents in pure.ts). They are tested with plain assertions, and they cannot go stale because they are recomputed from their inputs.
Lifting state to the closest common parent
The list and the cart must agree on what was added. React's recipe is to remove state from the children, move it to their closest common parent, and pass it down with the event handlers. In the lab the parent is the container. A test clicks Add Milk twice and Add Bread once and expects the cart to read "3 items, $4.90".
Figure 2. Data down, events up
How to read this: the row does not know the cart exists; it only knows a function to call. They meet in the container, which is why it is the owner.
Controlled and uncontrolled
A component with its own local state is uncontrolled: its parent cannot influence it. A component driven by props is controlled. With a local isOpen in each panel, the lab's panels can both be open and no parent can prevent it. With the state lifted into an accordion that stores one open index, opening a second panel closes the first, as in React's own example. The search input is controlled too: if the parent does not update the value, typing "bread" into a box whose parent still says "milk" leaves "milk" on screen (a lab test).
Container and view
The lab splits the page into two halves. The container (ProductBrowser) is a hook plus a view, and has no markup of its own:
export function ProductBrowser({ source }: { source: ProductSource }) {
return <ProductBrowserView {...useProductBrowser(source)} />;
}
The view (ProductBrowserView) is a pure function of its props with three branches: loading, error with a retry button, and ready. Each status is a prop value, so a test renders all three with no data loading.
This is the old "container and presentational" idea. Dan Abramov, who popularised it, later wrote that he no longer suggests splitting components that way, because hooks separate stateful logic without an arbitrary division. Keep the seam, not the ritual: one place decides state and effects, one place decides markup.
A custom hook shares logic, not state: each call to a hook is completely independent of every other call. In the lab, two ProductBrowser instances sit side by side, and adding milk to the left cart leaves the right one at "0 items".
Figure 3. Deciding where something goes
props or existing state?"} -->|yes| D["Derive it during render
(not state)"] Q1 -->|no| Q2{"Who needs it?"} Q2 -->|"one component"| L["Local state"] Q2 -->|"several siblings"| P["State in the closest
common parent"] Q2 -->|"logic only, no UI"| F["Plain function
(pure.ts)"]
How to read this: always try the top branch first. Most "state" bugs are values that should have been derived.
The failure case
Illustration 3: a component defined inside another
React's guidance is blunt: never define a component inside another, because it is very slow and causes bugs. React keeps state only while the same component is rendered at the same position, and a function declared inside a component is a different function on every render. React sees a different component at the same position and resets all state below it. The lab's BadHost declares Counter inside itself:
export function BadHost() {
const [renders, setRenders] = useState(0);
function Counter() {
const [count, setCount] = useState(0);
return (
<button type="button" onClick={() => setCount(count + 1)}>
{`Count ${count}`}
</button>
);
}
// ... renders a "Re-render host" button and <Counter />
}
Click the counter twice and it reads "Count 2"; click "Re-render host" and it reads "Count 0". The same counter declared at the top level keeps "Count 2" through the same click.
Trade-offs
| Choice | What it buys | What it costs | Choose it when |
|---|---|---|---|
| Many small components | Narrow tests, reuse, clear ownership | More files, more props to pass | A part has its own job or is repeated |
| State in a container | One owner, easy to reason about | Props passed down a few levels | Siblings share data |
| State local to a component | No wiring | Parent cannot coordinate it | Nobody else cares |
| Hook for logic, view for markup | Logic and markup tested apart | An extra seam to name | Stateful logic is bigger than the markup |
Build it: the product browser, tested with props and a fake source
Goal. Run the 22 tests, then print the framework-free half of the lab.
Setup. The lab is in the course's example workspace (Node 26, pnpm). The tests run under jsdom, a JavaScript model of the DOM with no layout or painting.
cd examples/frontend
pnpm install
cd labs/react-component-boundaries
pnpm test # 22 tests in one file, jsdom
node src/demo.ts
Steps.
- Read
test/boundaries.test.tsxin its seven groups: pure logic, presentational parts, a controlled input, the view per status, the container with a fake source, controlled versus uncontrolled panels, and the nested-definition failure. - Run the demo. Node cannot run
.tsxfiles, so it prints only the parts with no React. Section 2 shows the source failing once and then succeeding, which the retry button relies on.
Expected output, captured from a real run (Node 26.13.1, 2026-11-19):
=== 1. pure functions: derived values are computed, not stored
formatPrice(120) = $1.20
filter "" -> Milk, Bread, Eggs, Oat milk
filter " MILK " -> Milk, Oat milk
filter "zzz" -> (none)
cart {"milk":2,"bread":1} -> 3 items, $4.90
=== 2. the container's only outside dependency: a source that can fail once
attempt 1: error, catalogue unavailable (calls so far: 1)
attempt 2: ready, 4 products (calls so far: 2)
What the lab does not show. No real browser, so no layout, focus or paint. Component behaviour is asserted by the tests, not by this output, and the fake source stands in for a network.
Break it. (1) In src/components/presentational.tsx, delete disabled={!product.inStock} from the button: the out-of-stock test fails, because the button is now enabled. (2) In src/pure.ts, change query.trim().toLowerCase() to query.trim(): the case-insensitive filter test fails. With both changes applied together, exactly those two tests failed and 20 passed. Revert both and run the tests again: all 22 pass.
Stretch. Add an onRemove callback to ProductRow and to the container, with a test for each, and check that ProductBrowserView needs no change except the props type.
In practice: a 900-line product page that three teams edit
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The ShopStream product page is one component of about 900 lines (illustrative). It loads products, holds the search text, cart and a promotion banner, and renders all of it. Three teams touch the file, merge conflicts are weekly, and the only test renders the whole page against a mocked network.
Starting architecture
Figure 4. Starting point: one component owns everything
How to read this: every change goes through one file, and the only safety net is a test that needs the whole page and a mocked network.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Split by data model: container, view, presentational parts | Ownership, small tests, fewer conflicts | Props to thread, a naming convention | Over-splitting into trivial wrappers |
| Leave it, add more page tests | No refactor | Slower tests, same conflicts | Cost grows with the file |
The decision
| Field | Decision record |
|---|---|
| Context | One 900-line component, weekly merge conflicts, one slow page test. |
| Decision | Split along the data model: pure functions, then a container hook, a view with one branch per status, and presentational parts. Every component is declared at the top level of its file. |
| Consequences, good | Props-only tests per part; teams own separate files. |
| Consequences, bad | More files and prop plumbing. |
| Revisit when | The same props pass through more than three levels. Then consider context. |
Rollout and verification
- Extract the pure logic (filter, totals, formatting) with plain tests.
- Extract presentational parts one at a time, keeping the page's output unchanged.
- Introduce the container hook and the view, with a test per status including retry.
- Add a review rule against nested component definitions, and keep the old page test until the new ones cover the same behaviour.
The 2 a.m. failure
After the split, a promotion filter panel is written as a helper function inside ProductPage "to reach the state easily". Support reports that typing in its box keeps losing the text (illustrative). The panel is a new component type on every render, so React replaces it and the state it kept for itself resets. Tests passed because each typed one character with no parent re-render.
First three checks: (1) look for a component declared inside another component's body; (2) confirm in a test that the panel's state resets when the parent re-renders; (3) check whether the input's value lives in the child or the container. Mitigation: move the panel to the top level of the file and pass the state it needs as props. Follow-up: a test that re-renders the parent mid-typing, and a lint rule against nested definitions.
Architect's notes
- Draw the tree from the data model, then ask of each box: what does it own, receive and report?
- Derive before you store. Every extra state variable is a way for two values to disagree.
- Put state in the lowest component that covers everyone who needs it.
- Prefer plain functions for logic that needs no React.
Common mistakes
- Defining a component inside another component. Its state resets whenever the parent re-renders.
- Copying props into state. The copy goes stale when the parent changes the prop.
- Storing derived values (counts, filtered lists) in state.
- Splitting by file size instead of by job, producing wrappers that only pass props along.
- Assuming a custom hook shares state between components.
- A controlled input whose
onChangedoes not update the value. It looks frozen.
Key takeaways
- A component is a function of props, state and context that returns markup, and it must be pure.
- Cut the tree along the data model; each component has one concern.
- Data flows down as props, events flow up as callbacks.
- Each piece of state has one owner: the closest common parent of everyone who needs it.
- Derive what you can compute; keep state minimal.
- A container-and-view split, or a hook and a view, puts state in one place and markup in another.
- Never nest component definitions.
Practice exercises
Exercise 1 — Starter (45 min): Take a screen you know, list its data model, draw the matching component tree and mark which box owns each piece of state.
Exercise 2 — Intermediate (2 hours): Add a "sort by price" control to the lab. Decide whether the sort order is state or derived, and add one props-only test for the control and one pure-function test for the sort.
Exercise 3 — Advanced (half day): Add a basket panel that lists the cart lines. Decide where the cart must live, keep the existing tests green, and note which components changed their props.
Related reading
In this course:
- Component Composition and API Design, the shapes component boundaries take.
- Keys, Lists and Identity in React, how React matches components across renders.
- React Reconciliation and the Virtual DOM, why the same position and type keep state.
- Dependency Injection and Separation of Concerns, the same seam for the network, clock and storage.
- Feature-Based and Modular Folder Structure, where the files of these components go.
Official documentation
- React: Your First Component, components, capital names, nesting and the rule against nested definitions.
- React: Thinking in React, hierarchy from the data model, what counts as state, and inverse data flow.
- React: Sharing State Between Components, lifting state up, controlled components and the single source of truth.
- React: Preserving and Resetting State, why state is tied to a position in the tree.
- React: Reusing Logic with Custom Hooks, hooks share logic, not state.