Lesson 165 of 296
Lifting state up and composition
What you will learn
- Sharing state between components by lifting it up
- Where state should live
- Composition with children and props that take elements
- Avoiding prop drilling with composition
- Compound components
On this page
Lifting state up
When two components need the same state, move it to their closest common parent, and pass it down as props, with functions to change it.
Example: an accordion where only one panel can be open at a time. Each panel cannot hold its own "open" state, because opening one must close the others.
function Panel({
title,
isOpen,
onToggle,
children
}: {
title: string;
isOpen: boolean;
onToggle: () => void;
children: ReactNode;
}) {
return (
<section>
<h3>
<button type="button" aria-expanded={isOpen} onClick={onToggle}>
{title}
</button>
</h3>
{isOpen && <div>{children}</div>}
</section>
);
}
function Faq() {
const [openIndex, setOpenIndex] = useState<number | null>(0);
const toggle = (i: number) => setOpenIndex((current) => (current === i ? null : i));
return (
<>
<Panel title="Delivery" isOpen={openIndex === 0} onToggle={() => toggle(0)}>
We deliver in 2 to 3 working days.
</Panel>
<Panel title="Returns" isOpen={openIndex === 1} onToggle={() => toggle(1)}>
Return within 30 days.
</Panel>
</>
);
}The state lives in Faq. Each Panel is now controlled by its parent: it receives isOpen and calls onToggle.
Where should state live?
- Find every component that reads or changes the state.
- Find their closest common parent.
- Put the state there (or higher, if needed).
But keep state as low as possible: state high in the tree causes more components to re-render. Moving state down to where it is used is called colocation (Lesson 172).
| Kind of state | Usually lives |
|---|---|
| One component's UI (is this dropdown open?) | In that component |
| Shared by siblings | Their common parent |
| Needed across much of the app (current user, theme) | Context or a state library (Lessons 169, 174) |
| Data from the server | A data-fetching library cache (Lesson 174) or server components (Part 13) |
| In the URL (filters, page number, search term) | The URL, so it can be shared and bookmarked |
Composition
Composition means building components by combining other components, often by passing elements in, instead of configuring one huge component with many props.
With children (Lesson 159):
function Modal({ title, children, onClose }: { title: string; children: ReactNode; onClose: () => void }) {
return (
<div role="dialog" aria-modal="true" aria-labelledby="modal-title" className="modal">
<h2 id="modal-title">{title}</h2>
{children}
<button type="button" onClick={onClose}>Close</button>
</div>
);
}The modal does not need to know what goes inside it.
With "slot" props for several areas:
function PageLayout({ sidebar, content }: { sidebar: ReactNode; content: ReactNode }) {
return (
<div className="layout">
<aside>{sidebar}</aside>
<main>{content}</main>
</div>
);
}Composition solves prop drilling
Instead of passing user through Layout → Header → UserMenu, build the element where the data is, and pass the element down:
function UserMenu({ user }: { user: { name: string } }) {
return <span>{user.name}</span>;
}
function TopBar({ right }: { right: ReactNode }) {
return <header className="top-bar">JobPrep {right}</header>;
}
function App2({ user }: { user: { name: string } }) {
return <TopBar right={<UserMenu user={user} />} />;
}TopBar never sees user. Try composition before reaching for context.
Compound components
A set of components that work together and share state privately, like HTML's <select> and <option>. Example API:
<Tabs defaultValue="details">
<Tabs.List>
<Tabs.Trigger value="details">Details</Tabs.Trigger>
<Tabs.Trigger value="reviews">Reviews</Tabs.Trigger>
</Tabs.List>
<Tabs.Panel value="details">...</Tabs.Panel>
<Tabs.Panel value="reviews">...</Tabs.Panel>
</Tabs>The parent Tabs holds the state and shares it with its parts through context (Lesson 169). UI libraries such as Radix UI use this pattern. Good to name in senior interviews.
How to say it in an interview
"When sibling components need the same state, I lift it to their closest common parent and pass the value and callbacks down, making the children controlled. I keep state as low as possible to limit re-renders, and keep shareable UI state like filters in the URL. For flexible components I prefer composition, passing children or element props as slots, which also avoids prop drilling, and for related parts like tabs I use compound components that share state through context."
Key words
| Word | Meaning |
|---|---|
| Lifting state up | Moving shared state to a common parent |
| Colocation | Keeping state close to where it is used |
| Composition | Building UIs by combining components |
| Slot | A prop that receives an element to place in a layout |
| Compound components | Components that work together and share state |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.