Advanced React 05 · Techniques🔓 free after sign-in
Component design patterns
Composition, compound components, render props, portals and error boundaries.
Loading lesson…
Advanced React 05 · Techniques🔓 free after sign-in
Composition, compound components, render props, portals and error boundaries.
Loading lesson…
You know how to write a component (lesson React basics 01). But once several places use it, wishes start coming: "I want an icon on the order", "two buttons in the footer here", "align the footer right here". The simplest thing is to add a prop each time:
<Cardtitle="Order"subtitle="no. 1234"icon="cart"showFooterfooterText="Pay"footerAlign="right"onFooterClick={pay}/>
A year later the component has thirty props and a forest of conditions inside. And the troubles multiply:
showFooter off but footerText filled in) and nobody knows what applies then.overflow: hidden, or an error in one chart that brings down the whole page.Design patterns are proven answers to these situations – ways to design a component so it can be used in many ways without you rewriting it all the time.
A finished toy car from a shop can only do what the manufacturer thought of. Lego is a different approach: a set of bricks that fit together, and you build what you need. A component with thirty props is a finished toy; the patterns in this lesson are ways to build bricks.
The table is a map of the lesson: the problem on the left, the pattern in the middle, the section on the right:
| Problem | Pattern | Section |
|---|---|---|
| a component has dozens of props for its look | composition: children and subcomponents | 1 |
| several components share state (tabs, an accordion, a menu) | compound components | 2 |
| the logic is the same, the look different every time | render props (or a custom hook) | 3 |
| sometimes the component should hold the state, sometimes the parent | a controlled / uncontrolled component | 4 |
| a window or a tooltip must render outside its parent | a portal | 5 |
| an error in one part must not bring down the whole page | an error boundary | 6 |
This is what a card looks like that started simple and then grew with every new requirement:
// ❌ A "prop explosion" – every requirement = a new prop<Cardtitle="Order"subtitle="No. 1234"icon="cart"showFooterfooterText="Pay"footerAlign="right"onFooterClick={pay}/>
What if a requirement comes for two buttons in the footer? Or for a link in the title? You add more props and the component fills up with conditions inside. It's a finished toy the manufacturer keeps reworking.
// ✅ Composition – the user puts together what they need// (Button and CartIcon are made-up components: a button and a cart icon)<Card><Card.Header icon={<CartIcon />}>Order <small>No. 1234</small></Card.Header><Card.Body>…</Card.Body><Card.Footer><Button variant="ghost">Back</Button><Button onClick={pay}>Pay</Button></Card.Footer></Card>
Card now handles only the frame, padding and shadows. The content is supplied by whoever uses it – and when they want two buttons, they just put them there. The component doesn't have to change for that.
And this is how the card is built inside. Each part just renders its frame and puts children into it (React basics 02):
function Card({ children }: { children: ReactNode }) {return <div className="card">{children}</div> // the frame and shadow}function CardHeader({ icon, children }: { icon?: ReactNode; children: ReactNode }) {return <h3 className="card-header">{icon}{children}</h3> // the icon (if any) and the heading}function CardBody({ children }: { children: ReactNode }) {return <div className="card-body">{children}</div>}function CardFooter({ children }: { children: ReactNode }) {return <div className="card-footer">{children}</div> // buttons side by side, on the right}// We store the subcomponents as properties of Card, so you can write <Card.Header>Card.Header = CardHeaderCard.Body = CardBodyCard.Footer = CardFooter
No condition, no showFooter. Whoever doesn't want a footer simply doesn't write <Card.Footer>. Whoever wants two buttons puts two there.
An orchestra: the conductor stands in the middle and the musicians watch them. Each musician knows when to play because they can see the conductor – not because someone passed them a note. And you, as the organiser, just decide on the line-up: how many violins, where the piano goes.
Compound components work the same way. They're a set of components that belong together – like <select> and <option> in HTML. The main component is the conductor: it holds the state and "broadcasts" it through a hidden context. The other components watch it. The user puts together the line-up.
// This is how the user uses it:<Tabs defaultValue="react"><Tabs.List><Tabs.Tab value="react">React</Tabs.Tab><Tabs.Tab value="vue">Vue</Tabs.Tab></Tabs.List><Tabs.Panel value="react">⚛️ A UI library</Tabs.Panel><Tabs.Panel value="vue">🟩 A progressive framework</Tabs.Panel></Tabs>
And this is how it's built inside. It's the context from Hooks 04 – only nobody outside sees it, because the Provider is hidden inside Tabs:
// The context: what the conductor broadcasts – which tab is active and a function to switchconst TabsContext = createContext<{ active: string; setActive: (v: string) => void } | null>(null)// A custom hook: listen to the conductor (just like useTheme in Hooks 04)function useTabs() {const ctx = use(TabsContext)if (!ctx) throw new Error('Tabs.* must be inside <Tabs>') // a Tab outside <Tabs> = a clear errorreturn ctx}// The conductor: holds the state and broadcasts itfunction Tabs({ defaultValue, children }: { defaultValue: string; children: ReactNode }) {const [active, setActive] = useState(defaultValue)return <TabsContext value={{ active, setActive }}>{children}</TabsContext>}// A musician: watches the conductorfunction Tab({ value, children }: { value: string; children: ReactNode }) {const { active, setActive } = useTabs() // picks up out of thin air what's active and the function to switchreturn (// aria-selected = tells screen readers which tab is selected<button aria-selected={active === value} onClick={() => setActive(value)}>{children}</button>)}function Panel({ value, children }: { value: string; children: ReactNode }) {const { active } = useTabs()return active === value ? <div>{children}</div> : null}// The wrapper around the tab buttons – just a frame, it needs no contextfunction List({ children }: { children: ReactNode }) {return <div role="tablist">{children}</div> // role="tablist" = "a list of tabs" for screen readers}Tabs.List = List // so you can write <Tabs.List> (like Card.Header in section 1)Tabs.Tab = TabTabs.Panel = Panel
What happens after clicking the "Vue" tab:
Tab with value="vue" calls setActive('vue') – a function it got from the context.Tabs changes. It broadcasts a new context value.Tabs and Panels re-render: the "Vue" button is active, the React panel returns null, the Vue panel shows up.The component's user deals with none of this. They don't pass active or onChange to every button. And yet they can put anything of their own into the line-up – an icon, a badge, a separator.
What you see: The tabs from the example above. The Svelte tab has its own "new" badge – the component's user put it there themselves, without Tabs needing a prop for badges.
Try it:
CompoundTabsDemo at the bottom. Notice that no Tab gets active or onClick – it takes everything from the context.useId() in the code – a hook that makes a unique ID. Thanks to it the IDs for screen readers are unique, even if there were several sets of tabs on the page.The takeaway: The conductor holds the state, the musicians watch it, the user puts together the line-up. The logic is in one place, the structure is free.
Loading the interactive part…
A photo booth at the station takes care of the light, the countdown, the click and the printing. Only the pose is up to you. The booth doesn't need to know whether you'll smile or pull a face.
A render prop is the same idea: the component handles the logic (filtering, paging, the empty state) and gets a function from you that says what one item should look like.
function FilterableList<T>({ items, getText, renderItem }: {items: T[]getText: (item: T) => stringrenderItem: (item: T) => ReactNode // ← the render prop}) {const [query, setQuery] = useState('')const filtered = items.filter((i) => getText(i).toLowerCase().includes(query.toLowerCase()))return (<><input value={query} onChange={(e) => setQuery(e.target.value)} /><ul>{filtered.map(renderItem)}</ul> {/* the caller supplies the look */}</>)}// The same logic, two different looks:<FilterableList items={products} getText={(p) => p.name}renderItem={(p) => <li key={p.id}>{p.name} – <b>${p.price}</b></li>} /><FilterableList items={colors} getText={(c) => c}renderItem={(c) => <li key={c}>🎨 {c}</li>} />
Let's take it apart:
renderItem: it gets one item and returns what it should look like.getText is a second function from the caller: it says which text to search the item by. For products it's the name, for colours the colour itself.filtered.map(renderItem) calls renderItem for every filtered item – it's the same as filtered.map((item) => renderItem(item)) (JavaScript 04). The resulting JSX goes into the <ul>.FilterableList doesn't know whether it renders products or colours. It only knows how to search and where to put the items. It orders the look from you.What you see: Two lists built from the same FilterableList component. On the left products with a price, on the right colours with an icon and their own text for an empty result.
Try it:
The takeaway: The logic is written once and each use decides the look. The component doesn't need to know what the items look like.
Loading the interactive part…
The thermostat in a flat has two modes. In automatic mode it watches the temperature itself. In manual mode you set it and it just obeys. It's still the same device – only who decides is different.
A good UI component works the same way – exactly like <input> from Advanced React 01, which the parent controls with value and onChange, and which keeps its value itself with defaultValue:
<Switch defaultChecked /> – automatic: it keeps its state itself (uncontrolled).<Switch checked={wifi} onChange={setWifi} /> – manual mode: the parent keeps the state (controlled).One custom hook (Hooks 05) handles both modes. It gets the value from the parent (or undefined when none was sent), a default value for automatic mode and a function to call on a change:
// <T> = the type of the value (boolean for a switch) – see the box about generics in section 3function useControllableState<T>(controlled: T | undefined, defaultValue: T, onChange?: (v: T) => void) {const [internal, setInternal] = useState(defaultValue) // its own memory for automatic modeconst isControlled = controlled !== undefined // did we get a value from outside?const value = isControlled ? controlled : internal // who decidesconst setValue = (next: T) => {if (!isControlled) setInternal(next) // in automatic mode, write it down yourselfonChange?.(next) // always let the parent know (if it sent onChange)}return [value, setValue] as const // return a pair, like useState}// The component uses the hook and doesn't care which mode it's in:function Switch({ checked, defaultChecked = false, onChange }: {checked?: boolean; defaultChecked?: boolean; onChange?: (v: boolean) => void}) {const [on, setOn] = useControllableState(checked, defaultChecked, onChange)return <button role="switch" aria-checked={on} onClick={() => setOn(!on)}>{on ? 'On' : 'Off'}</button>}
Three things you haven't seen yet:
onChange?.(next) – a question mark and a dot before the brackets mean "call onChange only if it exists". It's the optional chaining from JavaScript 06, used on a function call. When the parent didn't send onChange, it's undefined and nothing happens (without the question mark it would crash with an error).as const – tells TypeScript the returned array always has exactly two items in this order: first the value, then the function. Without it TypeScript would think it's an array where either can be anywhere, and when unpacking const [on, setOn] = … it wouldn't know that setOn is a function.role="switch" and aria-checked – tell a screen reader that the button is a switch and whether it's on (more about aria-* attributes in the box by the challenges).What happens in the component:
checked. If it did, it's in manual mode and shows the value from the parent.onChange and waits for the parent to send a new value.onChange, nobody changes the value – the switch is read-only.What you see: Three switches of the same Switch component: the first in automatic mode, the second controlled by the parent (the wifi state), the third controlled without onChange. At the bottom, a button the parent uses to change wifi.
Try it:
wifi = … text in its label changes too – the parent holds the value and the switch only informs it.The takeaway: One component, two modes. The user chooses: let it manage by itself, or control it.
Loading the interactive part…
A class makes a poster about the school trip. If it hung only in the classroom, behind a cupboard, nobody would see it. So they pin it to the noticeboard in the hall. The poster still belongs to that class – they made it and look after it – it just hangs somewhere else.
Modals (windows over the whole page), tooltips (little help bubbles) and dropdown menus have the same problem. When you render them inside a card that has overflow: hidden or transform (CSS properties: the first clips everything that sticks out of the card, the second moves or scales it, say), the card clips or covers them. A portal renders them elsewhere in the DOM (typically into <body>), but in the React tree they stay where they are:
import { createPortal } from 'react-dom'function Modal({ children, onClose }: { children: ReactNode; onClose: () => void }) {return createPortal(<div className="modal-layer"><div className="modal-backdrop" role="presentation" onClick={onClose} /><div className="modal" role="dialog" aria-modal="true">{children}</div></div>,document.body, // where to "pin" it in the DOM)}
<body> – no card clips it.<body>. (Bubbling = a click is reported first to the element you clicked and then to each of its parents in turn – each one can react.)modal-layer holds both. If the window were inside the backdrop, a click on the content would "bubble up" to the backdrop and close the modal. This way the backdrop isn't the window's parent and a click inside the window never reaches it.role="dialog" and aria-modal="true" tell a screen reader that the window is a dialog and the page under it can't be used right now. role="presentation", on the other hand, says the backdrop is only decoration – that's why the modal must close without a mouse too (with a button or the Escape key, see the challenge "An accessible modal" below).What you see: A card with overflow: hidden and transform – a typical trap for modals. Two buttons open the same modal: once rendered in place, once through a portal.
Try it:
The takeaway: A portal changes where an element hangs in the DOM, but not whom it belongs to. An escape from clipping without losing context and events.
Loading the interactive part…
When the kettle shorts out in the kitchen, a fuse blows – but only for the kitchen. In the living room the lights stay on and the TV keeps running. If the whole flat were on one fuse, every short circuit would mean darkness everywhere.
Without protection, a React app behaves like a flat with one fuse: an error while rendering any component takes down the whole page – the user sees an empty white screen. An error boundary is a fuse for one part of the tree: it catches the error and shows fallback content in place of the crashed part.
<ErrorBoundary fallback={<p>The chart couldn't be displayed.</p>}><SalesChart /></ErrorBoundary><ErrorBoundary fallback={<p>The order list is unavailable.</p>}><OrderList /></ErrorBoundary>
When SalesChart throws an error while rendering (throw from JavaScript 07), React climbs up the tree to the nearest boundary above it and renders its fallback (stand-in content) instead of its contents. OrderList has its own boundary, so it keeps running.
Where does ErrorBoundary come from? React itself has no hook for it – it can only be written as a class component (an older way of writing components with class, which you don't need in this course). So in practice people use the ready-made react-error-boundary library (install it with npm install react-error-boundary). It can do a "Try again" button too:
import { ErrorBoundary } from 'react-error-boundary'<ErrorBoundary// fallbackRender: a function that returns the stand-in content (a render prop from section 3)// error = the error that happened; resetErrorBoundary = a function that renders the contents againfallbackRender={({ error, resetErrorBoundary }) => (<div role="alert"><p>The chart couldn't be shown: {error.message}</p><button onClick={resetErrorBoundary}>Try again</button></div>)}><SalesChart /></ErrorBoundary>
role="alert" tells a screen reader to read the message right away. After clicking "Try again" the boundary goes back to normal and tries to render SalesChart again – if the error was just a fluke, the chart shows this time.
What you see: Two widgets, each in its own boundary. Both crash on purpose at number 3 – they throw an error while rendering.
Try it:
The takeaway: Each boundary protects only its own part. An error in one widget doesn't take down the other or the rest of the page.
Loading the interactive part…
A boundary doesn't guard everything. The left column shows what it catches, the right one what it doesn't. The rule behind it: it guards rendering. Code that runs at other times – after a click, when a timer runs out, when a server response arrives – you have to handle yourself with try/catch (JavaScript 07). use() in the table is a hook that reads server data right during render – you'll meet it in Advanced React 08.
| A boundary catches | A boundary does NOT catch |
|---|---|
| Errors while descendants render | Errors in event handlers (use try/catch) |
| Errors in descendants’ effects | Asynchronous errors (setTimeout, a promise outside render) |
A rejected Promise in use() | An error in the boundary itself |
This section puts the lesson together into steps to come back to when you design your own component for several places. You'll find the same pattern in the Cheat sheets on the React tab.
children for content. Add a pattern only once the wishes really need it.Card.Header, Card.Footer).value + onChange, or defaultValue.// the file src/components/Tabs.tsximport { createContext, use, useState, type ReactNode } from 'react'// 1. THE HIDDEN CHANNEL – what the conductor broadcasts: the active tab and a function to switch; not exportedconst TabsContext = createContext<{ active: string; setActive: (v: string) => void } | null>(null)// 2. THE HIDDEN LOUDSPEAKER – a hook with a check (lesson Hooks 04)function useTabs() {const ctx = use(TabsContext)if (!ctx) throw new Error('Tabs.* must be inside <Tabs>') // a Tab outside <Tabs> = a clear errorreturn ctx}// 3. THE CONDUCTOR – holds the state and broadcasts it to everything insidefunction Tabs({ defaultValue, children }: { defaultValue: string; children: ReactNode }) {const [active, setActive] = useState(defaultValue)return <TabsContext value={{ active, setActive }}>{children}</TabsContext>}// 4. THE MUSICIANS – each takes what it needs from the contextfunction Tab({ value, children }: { value: string; children: ReactNode }) {const { active, setActive } = useTabs()// aria-selected = a screen reader knows the selected tab; a click switches to this onereturn <button aria-selected={active === value} onClick={() => setActive(value)}>{children}</button>}function Panel({ value, children }: { value: string; children: ReactNode }) {const { active } = useTabs()return active === value ? <div>{children}</div> : null // show up only when your tab is active}// 5. SUBCOMPONENTS AS PROPERTIES – so you can write <Tabs.Tab> (section 1)Tabs.Tab = TabTabs.Panel = Panelexport { Tabs } // only Tabs goes out, the context stays hidden// use in another file: import { Tabs } from './components/Tabs'<Tabs defaultValue="a"><Tabs.Tab value="a">First</Tabs.Tab><Tabs.Tab value="b">Second</Tabs.Tab><Tabs.Panel value="a">The first tab's content</Tabs.Panel><Tabs.Panel value="b">The second tab's content</Tabs.Panel></Tabs>
value + onChange) or left inside (defaultValue).One card, different content. You just need to render it in the right place.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
The accordion practises section 2: the user-facing API is finished, your task is to build the conductor and the musicians. The modal combines section 5 with refs and effects – and on top of that it has to work with the keyboard and a screen reader.
The API is finished – your task is to get the components working "under the bonnet". What should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
A modal that works with the keyboard and a screen reader – and that its parents' styles can't clip. What should happen is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
defaultX) and controlled (x + onChange).