Sub topic 12
Composition: Slot Props and Render Props
This chapter assumes you can write function components, destructure props, and use the children prop. It also assumes you know that JSX elements and functions are ordinary values you can pass as props. Earlier chapters cover those topics. Here you will use them to build components whose layout or output the parent controls.
Why composition
A reusable component often needs to render content it can't know in advance. A Layout doesn't know what goes in the header. A List doesn't know how to draw one row.
You could add a prop for every variation: headerText, headerIcon, headerIsBold. The list never ends. Composition avoids this. The component defines the structure, and the parent supplies the content, either as elements (slot props) or as a function that returns elements (render props).
Slot props
The children prop gives you one unnamed slot. When a component needs several areas, pass JSX elements through named props. Each prop is a slot.
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>Menu</nav>}>
<p>Main content</p>
</Layout>
);
}Layout decides where each area sits. App decides what each area contains. Layout never inspects the elements. It only places them.
Optional slots
A slot you don't pass is undefined. React renders nothing for undefined, null, false, and true, so the content is skipped safely. The wrapper tag around it still renders, though. An unused sidebar leaves an empty <aside> that can still take up space through CSS or confuse screen readers. Guard the wrapper as well:
function Layout({ header, sidebar, footer, children }) {
return (
<div className="layout">
{header && <header>{header}</header>}
{sidebar && <aside>{sidebar}</aside>}
<main>{children}</main>
{footer && <footer>{footer}</footer>}
</div>
);
}This guard has one trap. The value 0 is falsy but React renders it as text. If a slot might receive a number, write sidebar != null && ... instead.
You can also supply a default element in the destructuring, such as footer = <p>All rights reserved</p>. A parent can still pass footer={null} to remove it, because defaults apply only to undefined.
Elements versus component types
A slot can accept an element (icon={<StarIcon />}) or a component type (icon={StarIcon}). They differ in who controls rendering.
- With an element, the parent creates it and can set its props. The child can only place it.
- With a component type, the child renders
<Icon size={16} />itself and controls the props. A prop that holds a component type must be capitalized when you use it as a tag, so writeconst Icon = props.iconfirst.
Prefer elements for plain content. Use component types only when the child needs to configure what it renders.
Render props
A slot holds content the parent already built. Sometimes the child has data that the content depends on, such as the current list item, a hover state, or a loading result. In that case the parent passes a function, and the child calls it with that data. This is a render prop: a prop whose value is a function that returns JSX.
function List({ items, renderItem, empty = <p>Nothing here.</p> }) {
if (items.length === 0) return empty;
return (
<ul>
{items.map((item) => (
<li key={item.id}>{renderItem(item)}</li>
))}
</ul>
);
}
export default function App() {
const users = [
{ id: 1, name: 'Ada', online: true },
{ id: 2, name: 'Grace', online: false },
];
return (
<List
items={users}
renderItem={(user) => (
<span>
{user.name} ({user.online ? 'online' : 'offline'})
</span>
)}
/>
);
}List owns the iteration, the <ul> markup, the keys, and the empty state. App owns how a single row looks. The same List can render users, orders, or files.
This example uses both patterns. empty is a slot (an element), and renderItem is a render prop (a function).
Function as children
The function can also be passed as children. The call site then reads like nested markup:
import { useState } from 'react';
function Toggle({ initial = false, children }) {
const [on, setOn] = useState(initial);
return children({ on, toggle: () => setOn((value) => !value) });
}
export default function App() {
return (
<Toggle>
{({ on, toggle }) => (
<div>
<button onClick={toggle}>{on ? 'Hide' : 'Show'} details</button>
{on && <p>Here are the details.</p>}
</div>
)}
</Toggle>
);
}Toggle holds state and renders no markup of its own. It only shares behavior. The state lives in Toggle, but the parent decides what the interface looks like.
Render props and hooks
Before hooks existed, render props were the standard way to share stateful logic. For logic reuse, a custom hook is now usually simpler:
import { useState } from 'react';
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = () => setOn((value) => !value);
return [on, toggle];
}
export default function Details() {
const [on, toggle] = useToggle();
return (
<div>
<button onClick={toggle}>{on ? 'Hide' : 'Show'} details</button>
{on && <p>Here are the details.</p>}
</div>
);
}The hook version has no nested function and no extra component in the tree. Render props still make sense when the child must control where and how often your content renders. Lists, virtualized grids, and tooltips are common cases. In those cases the child calls your function once per row or only while visible, and a hook can't do that.
Choosing a pattern
| Situation | Use |
|---|---|
| One block of content inside a wrapper | `children` |
| Several fixed areas in a layout | Slot props |
| Content depends on data only the child has | Render prop |
| Reusing stateful logic, with no layout concern | Custom hook |
| Many levels must read the same value | Context (next chapter) |
Gotchas
Hooks inside a render prop function
The function you pass as a render prop is not a component. React doesn't treat it as one, and it runs inside the child's render. If you call useState inside renderItem, the hook becomes part of List's hook order. When the number of items changes, the number of hook calls changes, and React throws an error about rendering a different number of hooks.
Fix this by having the render function return a component element, which gets its own state:
function UserRow({ user }) {
const [expanded, setExpanded] = useState(false);
return (
<button onClick={() => setExpanded(!expanded)}>
{expanded ? `${user.name} (online)` : user.name}
</button>
);
}
<List items={users} renderItem={(user) => <UserRow user={user} />} />Inline functions and memoization
renderItem={(user) => ...} creates a new function on every parent render. If List is wrapped in memo, the shallow comparison sees a changed prop and re-renders anyway. Wrap the function in useCallback only when profiling shows a problem. Inline JSX slots have the same property: header={<h1>Hi</h1>} creates a new element each render, so it also defeats memo.
Keys belong to the child
List set the key on the <li> it created. If your render prop returned the <li> itself, the key would need to go on the returned element. Decide which side owns the list item tag and document it. The usual rule is that the component that calls map sets the key.
Defining components inside a render function
Don't define a component inside another component and pass it as a slot type. A new function identity on each render makes React unmount and remount that subtree. The result is lost state and lost input focus. Define components at module level.
Exercise
A Panel component renders <aside>{sidebar}</aside> and a parent sometimes omits the sidebar prop. The page shows an empty gap where the aside is. What causes it, and how do you fix it?
Show answer
When sidebar is undefined, React renders nothing inside the aside, but the <aside> tag itself still renders and can take up space through CSS. Fix it by rendering the wrapper only when the slot has a value: {sidebar != null && <aside>{sidebar}</aside>}. Using != null rather than && on the raw value avoids printing a stray 0 if the slot could be the number 0.
Exercise
You write <List items={users} renderItem={(user) => { const [open, setOpen] = useState(false); return <li>{user.name}</li>; }} />. The app crashes when the user list gets shorter. Why, and what is the fix?
Show answer
The render prop runs inside List's render, so its useState call becomes one of List's hooks. A different number of items means a different number of hook calls between renders, which breaks the rules of hooks. Move the state into a separate component such as UserRow, and have the render prop return <UserRow user={user} />. Each row then has its own state.