React / 14
Composing components
Build big UIs from small components used inside each other. Render them as tags, never call them as functions, and never define one inside another.
A page is a tree of components
- <App />
- <Header />
- <Logo />
- <CartBadge />
- <MenuList />
- <MenuCard />
- <MenuCard />
- <MenuCard />
- <Footer />
- <Header />
what the user sees
Using a component inside another is composition. Every React app is one tree like this, with App at the root.
Snap them together
function Logo() {
return <h1 className="logo">Tasty Bites</h1>;
}
function Header() {
return (
<header>
<Logo />
<nav>Menu · Offers · Cart</nav>
</header>
);
}
export default function App() {
return (
<>
<Header />
<main>{/* <MenuList /> goes here */}</main>
</>
);
}React renders App, finds <Header />, renders Header, finds <Logo />, renders Logo, and so on down the tree. The final page is as if you'd written all the JSX in one place, but each piece lives in its own small function.
Right now each MenuCard would show the same dish. The next chapter adds props, which let a parent pass data down (<MenuCard name="Dosa" price={80} />). That's where composition gets really powerful.
Render it, don't call it
A component is a function, so {Title()} seems to work too. Don't.
Don't
Calling it like a function
<div>{Title()}</div>The function runs as part of the parent. Any hooks inside (like useState) become the parent's hooks, and break the rules of hooks the moment you call it conditionally. It also has no name in React DevTools.
Do
Rendering it as a tag
<div><Title /></div>This creates an element. React calls Title itself, at the right time, and gives it its own spot in the tree with its own state.
<Title></Title> is the same as <Title />. Use the long form only when you put children between the tags.
Define components at the top level
Each render, the parent's function body runs again. A component defined inside it is a brand-new function every time, and React compares components by identity. New function, new component type: React throws the old one away, DOM and state included, and mounts a fresh one.
Defined outside vs inside
Try it✓ defined outside
parent rendered 1×
✗ defined inside the parent
parent rendered 1×
Don't
Inside the parent
function MenuList() {
const MenuCard = () => <input placeholder="Note" />;
return <MenuCard />;
}Do
Next to it, at the top level of the file
function MenuCard() {
return <input placeholder="Note" />;
}
function MenuList() {
return <MenuCard />;
}Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
