An online pharmacy app grows from a handful of screens to dozens of them, and its folder layout starts to matter. Most projects begin by sorting files by what they are: a components folder, a hooks folder, a utils folder.
That layout works until the app has three hundred components. A change to the cart then touches the cart component in one folder, its hook in another, its helpers in a third and its tests in a fourth. Nothing in the layout says which of those belong together, so every file can import every other file, and over time every file does.
Folders by feature
A feature folder groups everything one part of the product needs: its components, hooks, state, API calls and tests. For the pharmacy, cart and prescriptions are features. Pages and the app shell live in a separate app folder and assemble features. Anything several features share, such as a button or a date formatter, goes in a shared folder.
Dependencies then follow one direction. The app folder may import from features, features may import from shared, and shared imports from neither. A feature importing another feature is allowed only through that feature's public entry point, an index file that exports what the rest of the codebase may use. Everything else in the folder is private.
The point of the entry point is freedom. If cart renames an internal file, splits a hook in two or swaps its storage, only the cart folder changes, as long as the exports in index still work. Without it, every deep import is a promise the folder cannot break.
Enforcing the rule with a linter
Rules that depend on people remembering them fail slowly. A linter can state this one in a few lines. ESLint's no-restricted-imports rule accepts gitignore-style patterns, and the pattern below matches any import of a file two levels inside a feature folder.
The lab project has the layout described above, with one page that imports the feature index files correctly and one deep import of each feature. The script prints the folder tree and the linter's findings.
text
src tree:
app/
Checkout.jsx
features/
cart/
CartLine.jsx
cart-store.js
index.js
prescriptions/
index.js
rules.js
eslint:
src/app/Checkout.jsx:2:1 no-restricted-imports
'../features/cart/cart-store' import is restricted from being used
by a pattern. Import the feature through its index file.
src/app/Checkout.jsx:4:1 no-restricted-imports
'../features/prescriptions/rules' import is restricted from being
used by a pattern. Import the feature through its index file.
Real run with ESLint 10. Long messages are wrapped to fit.
The imports of ../features/cart and ../features/prescriptions passed, because they name the folder and not a file inside it. The two deep imports were reported at their line and column, with the message appended. The lab uses plain JavaScript so that ESLint needs no extra parser. A TypeScript project adds the TypeScript parser and keeps the same rule.
What the rule does not do
The linter reads the text of the import path, so it cannot see imports built at run time, and it will not notice a feature that exports far too much from its index. It also does not stop circular dependencies between two features, where cart imports prescriptions and the reverse. Plan for that by keeping dependencies one way: if two features need each other, the shared part probably belongs in a third place.
Start with feature folders before the app is large. Moving files in a small project takes an afternoon, and in a large one it takes a quarter. The rest of this chapter assumes the layout and asks where each kind of state should live inside it.
Check your understanding
What does a feature folder's index file do?
It is the public entry point. It exports what other code may use, so everything else in the folder can change without breaking importers.
Why did the import of ../features/cart pass the lint rule while ../features/cart/cart-store failed?
The pattern matches paths two levels inside a feature folder. The first names the folder itself, which resolves to its index file.
Name one thing the import rule cannot catch.
Circular dependencies between two features. It also cannot see imports built at run time.
Part 2 · Where each kind of state belongs
Six kinds of state
State is not one thing. Putting every kind into one global store makes each of them harder to handle, because they differ in who needs them, how long they live and who owns the truth. Naming the kind first usually decides where it goes.
Kind
Example in the pharmacy
Home
Why there
Local
whether a dropdown is open
useState in the component
only that component cares
Lifted
quantity shared by a row and the totals
useState in the nearest common parent
siblings need the same value
URL
category, sort order, page number
the address bar
shareable, bookmarkable, back button works
Server
the medicine catalogue, past orders
a server-state cache
the server owns it and it can go stale
Form
text typed into the address form
form state
short-lived, discarded after submit
Global client
cart contents, display language
context or a store
many distant components need it
Local
Example in the pharmacywhether a dropdown is open
HomeuseState in the component
Why thereonly that component cares
Lifted
Example in the pharmacyquantity shared by a row and the totals
HomeuseState in the nearest common parent
Why theresiblings need the same value
URL
Example in the pharmacycategory, sort order, page number
Homethe address bar
Why thereshareable, bookmarkable, back button works
Server
Example in the pharmacythe medicine catalogue, past orders
Homea server-state cache
Why therethe server owns it and it can go stale
Form
Example in the pharmacytext typed into the address form
Homeform state
Why thereshort-lived, discarded after submit
Global client
Example in the pharmacycart contents, display language
Homecontext or a store
Why theremany distant components need it
Two rows deserve a closer look because they are often placed wrongly. Server state is a copy of something that lives elsewhere. Copying it into a global store makes you responsible for knowing when it is out of date. The previous chapter hand-built a cache for it, and a client cache library does the same job with more care. URL state is the one beginners forget. If a filter lives only in useState, a refresh loses it and a shared link cannot restore it.
Keeping filters in the URL
The pure function below turns query parameters into a filter object. It validates every value, so a hand-edited address cannot put the page into a state the code never expected. The page reads it through React Router's useSearchParams, which the router chapter introduced.
The test opens the page at a URL, clicks the stock filter, then opens a second, brand new router at the address the first one ended on. It finishes with a hand-damaged URL.
text
open /medicines?category=pain&sort=price
shows: Paracetamol 500, Ibuprofen 400
click "In stock only" -> /medicines?category=pain&sort=price&stock=1
shows: Paracetamol 500
new router opened at the saved URL, no state kept in memory
shows: Paracetamol 500
bad URL -> falls back: Cetirizine 10, Ibuprofen 400, Paracetamol 500
Real run in jsdom with a memory router.
The click changed the address to include stock=1, and the list changed with it. A new router created from only that address showed the same list, which is what a refresh or a pasted link does. The damaged address fell back to the defaults and showed all three medicines sorted by name, with no error.
A rule for choosing
Ask three questions in order. Does the server own it? Then it is server state. Should a link or a refresh restore it? Then it is URL state. Is it used by one component or two neighbouring ones? Then it is local or lifted. Only what is left, shared by distant parts of the screen and owned by the client, belongs in context or a store.
Try the questions on three more items from the pharmacy. The text in the search box is local until the page needs it in the address, and then it is URL state. The list of the shopper's past orders is server state. The delivery address being typed at checkout is form state. Each lands in a different home, and none of them needs a global store.
The list is shorter than people expect. In a typical app, once server state and URL state are moved out, the global client state is a few small things: the cart, a theme, a signed-in user. That is why a store with dozens of slices is often a sign that the other kinds were put in the wrong home.
Check your understanding
Where should the selected category of a product list live, and why?
In the URL. A refresh keeps it, a link shares it, and the back button moves between filters, as the second router in the run showed.
Why validate each query parameter in readFilters?
Anyone can edit the address. The damaged URL in the run fell back to defaults instead of putting the page in an unplanned state.
Why is copying fetched data into a global store a problem?
The server owns the data, so the copy can go stale and you are then responsible for refetching and invalidating it.
Part 3 · Structuring state so bugs have nowhere to live
Principles from the react.dev guide
The react.dev guide on choosing the state structure gives principles that remove whole classes of bug. This lesson runs two of them: avoid duplicated state and avoid contradictory state. The other principles it lists are to group related state, to avoid redundant state that can be calculated during render, and to avoid deep nesting.
Duplicated state
A cart panel lets the shopper select a line to see its details. The first version stores the selected line itself. The cart list and the details panel then hold two copies of the same object.
The test selects the first line and adds one to its quantity in both versions.
text
copy: after select -> Paracetamol x1
copy: after add (list shows Paracetamol x2) -> Paracetamol x1
by id: after add (list shows Paracetamol x2) -> Paracetamol x2
Real run. "list shows" is the row in the cart list.
In both runs the list showed quantity 2. The copy version still said "Paracetamol x1" in the details, because the selected object was a snapshot taken at the click and the list update never touched it. The id version said "x2". The copy version did nothing wrong except exist: it is a second place that needed updating, which is exactly what goes wrong as a screen grows. With the id, there is one place that holds the truth.
Contradictory state
The next component tracks an order in flight with two booleans. The code has a bug: it forgets to reset sending.
two flags: sending=true sent=true
one status: status=editing > status=sending > status=sent
Real run. Both components were clicked and given 30 ms to finish.
The boolean version ended with sending=true sent=true, a combination no screen should show, and any code that reads either flag gets a different answer. The status version went from editing to sending to sent, and no sequence of calls can make it say two things. The request state union in the data fetching chapter is the same idea with more variants.
Duplication is not always wrong. A form that edits a quantity before saving should hold a copy, because the draft must not change the cart until the shopper confirms. The difference is intent: a draft is a separate value on purpose, and a stale detail panel is a copy by accident. When you do copy, name the copy a draft and decide when it is thrown away.
Practical habits
Store ids and look the object up. The lookup is one line, and it removes the stale copy.
Prefer one status field with named values to several booleans that must agree.
Do not store anything you can calculate from state during render, such as totals or counts. Calculate it, as the state and effects chapter showed.
Flatten deeply nested state into maps keyed by id when an update has to reach inside it.
A related habit is to group state that always changes together. A map cursor with separate x and y variables invites updates that change one and forget the other, while one { x, y } object moves as a unit. The react.dev guide lists this principle first, and it pairs naturally with deriving values: the fewer independent variables you hold, the fewer combinations exist.
These are design habits, and the compiler will not enforce most of them. The reward is that a bug like the stale detail panel cannot be written in the first place.
Check your understanding
Why did the details panel show x1 in the copy version?
The selected object was a snapshot taken at the click. The list update created a new object and never touched the copy.
What does storing selectedId change?
There is one copy of each line. The panel looks the line up during render, so it always shows the current quantity.
How does a single status value prevent the sending-and-sent bug?
It holds exactly one value at a time, so two contradictory flags cannot both be true.
Part 4 · Context at scale
What a provider costs
The advanced hooks chapter showed that every component reading a context renders again when the provider's value changes. In a large app that fact becomes a design constraint. If the pharmacy put the cart, the prescriptions and the actions in one context, a new prescription would render every cart component too.
react.dev's guide on scaling up with reducer and context describes the pattern most apps start from: one context for the state, one for the dispatch function, and a provider component that holds the reducer. Components that only dispatch then do not render when the state changes. This lesson measures what happens as the contexts multiply.
One context against three
The first version puts the lines, the prescriptions and both actions in one value.
The second version separates them into a cart context, a prescription context and an actions context. The actions object is memoised, so its identity never changes.
Each version has a cart badge, a prescription badge and a pair of buttons below a memoised shell. The test adds a line and then a prescription, and counts which components render.
text
one context, add a line: CartBadge 1, RxBadge 1, Buttons 1
one context, add an rx: CartBadge 1, RxBadge 1, Buttons 1
split contexts, add a line: CartBadge 1
split contexts, add an rx: RxBadge 1
Real run, React 19.3.1, StrictMode off. Counts are renders per action.
With one context, each action rendered all three consumers, including the buttons that only needed the actions. With the split, a new line rendered the cart badge alone and a new prescription rendered the prescription badge alone. The buttons never rendered because their context never changed.
Animated sceneOne big context against split contexts0:18
Watch for which consumers render when only the cart changes
Read it as steps
After the split, a cart change reaches only the cart consumer
Provider values must be stable
Splitting is not the only cost to watch. A provider can make every consumer render with no state change at all. When a component renders a provider, it creates a new value object unless you stop it. A new object is a changed value to React, so every consumer renders, even if the contents are identical.
The test re-renders the parent of the provider with an unrelated counter. Both versions sit below a memoised child, so the only route to the consumer is the context.
text
parent re-renders, memoised value no : TotalsReader 1
parent re-renders, memoised value yes: nothing rendered
Real run. A parent re-renders with an unrelated counter.
With a fresh value object every render, the consumer rendered when its parent ticked. With useMemo, nothing rendered.
Reading one part of a big context
Sometimes the context cannot be split, because it belongs to a library or to another team. The react.dev page for memo describes a way out: read what you need from the context in an outer component, and pass it down as a prop to a memoised child. The outer component still renders when the context changes, but the child, which holds the expensive work, renders only when its own prop changes.
The provider holds lines and rx in one value. The test adds a line, which changes the value but leaves the rx array the same, once for each version.
text
direct add a line: RxDirect 1
outer and inner add a line: RxOuter 1
Real run. Adding a line leaves the prescription list unchanged.
The direct reader rendered because the context value changed. The outer component also rendered, since it reads the context, but RxInner did not, because its rx prop was the same array as before. Use this when the child is costly, and leave it out when the child is as cheap as the wrapper that guards it.
A rule of thumb
Finding an over-rendering context is a measurement job, not a guess. A counter in each component body, as in these runs, answers whether it rendered. React's Profiler component, which the next chapter uses, reports which subtrees rendered for a commit and how long they took. Measure before splitting, because a context read by three small components costs almost nothing.
Split contexts by how often they change and who reads them: state that changes often apart from state that rarely changes, and actions apart from both. Memoise a provider's value. If one context still causes too many renders, that is the moment to move to a store with selectors, which the next lesson builds.
Check your understanding
Why did the buttons not render in the split version?
They read only the actions context. Its value is memoised, so its identity never changed.
A provider writes value={{ lines, addLine }}. What goes wrong when its parent re-renders for another reason?
The inline object is new every time, so React treats the value as changed and renders every consumer. useMemo avoids it.
What did splitting change for the prescription badge when a line was added?
It stopped rendering. It reads only the prescription context, which did not change.
Part 5 · Client stores with selectors
Why a store
Context cannot let a component say "tell me only when this slice changes". Any change to the value renders every reader. A client store keeps state outside React and lets each component subscribe through a selector: a function that picks the part of the state the component needs. The component renders again only when the selected value changes.
The advanced hooks chapter introduced useSyncExternalStore, which is the primitive underneath. A store is that hook with a subscription list and a selector.
A store in under thirty lines
The function below keeps the state in a variable and a set of listeners, and offers getState, setState and subscribe. The hook passes a snapshot function that runs the selector.
Three components read the same cart state, each through its own selector: a row that selects its own line, a total that sums every line and a prescription panel that selects the prescription count.
tsx
const store = createStore<Shop>(initial)
function Row({ id }: { id: string }) {
hit(`Row ${id}`)
const line = useStore(store, (s) => s.lines.find((l) => l.id === id)!)
return (
<li>
{line.name} x{line.qty}
</li>
)
}
function Total() {
hit('Total')
const total = useStore(store, (s) =>
s.lines.reduce((sum, l) => sum + l.qty * l.price, 0),
)
return <p>total {total}</p>
}
function RxPanel() {
hit('RxPanel')
return <p>{useStore(store, (s) => s.rx.length)} prescriptions</p>
}
The same thing in Zustand
Zustand is a small library for this idea. create returns a hook that takes a selector, and it needs no provider. The components differ from the hand-written ones only in the hook they call.
The test edits the quantity of the first line in each store.
text
own store, edit p1: Row p1 1, Total 1
zustand, edit p1: Row p1 1, Total 1
Real run. Counts are renders after the edit.
Both stores rendered the edited row and the total. The second row and the prescription panel did not render at all, because the lines they selected were the same objects as before, and a React component skips a render when its selected value is equal by Object.is. The total rendered because its number changed.
Animated sceneOne cart line changes in a store0:15
Watch for which components render when one line's quantity changes
Read it as steps
Only the edited row and the total render; the prescription panel does not
The trap: selectors that build new objects
Stores make this class of bug easy to hit, so learn its shape. A selector that returns a new object every time looks harmless. It is not, because the store treats a new reference as a change.
selector returning a new object, no useShallow:
console.error: The result of getSnapshot should be cached to avoid
an infinite loop
render threw: Maximum update depth exceeded. This can happen when a
component repeatedly calls setState inside componentWillUpdate or
componentDidUpdate. React limits the number of nested updates to
prevent infinite loops.
with useShallow, change a quantity: nothing
with useShallow, add a third line: Summary 1
Real run with Zustand 5.1.0. The first block is the unfixed selector.
React printed the same snapshot warning as in the advanced hooks chapter and stopped with its update-depth error. The cause is different here: the selector returned a new object, so each check of the snapshot looked like a change and scheduled another render. The fix is useShallow, which compares the fields of the returned object one by one. It is imported from zustand/react/shallow: the installed 5.1.0 package has a react/shallow type file that declares useShallow<S, U>(selector), and its top-level zustand/shallow file re-exports the same function.
With it, changing a quantity rendered nothing, since neither count changed, and adding a line rendered the summary once. If you can select primitives, selecting them one per call is simpler than any helper.
Stores also suit state that changes from outside React. A WebSocket handler or a timer can call setState on the store directly, with no component involved, and every subscribed component updates. The selector can live outside the component too, which makes it a plain function you can test without rendering.
The test mounts Total, lets a timer add a line to the store from outside React, then calls the selector directly and unmounts the component.
text
on mount: total 22
after a timer outside React: total 76
selector as a plain function: 76
after unmounting the component, the store still holds 2 lines
Real run with the hand-written store. The timer never touches a component.
The component updated from 22 to 76 although nothing inside React caused it, and the same selector gave 76 as a plain function. The last line is the caution for tests: the state lives in the module, so it survives the unmounted component and the next test would start from it. Reset a module-level store in a setup step.
Check your understanding
Why did the second row not render when the first row's quantity changed?
Its selector returned the same line object as before, and a store hook skips the render when the selected value is equal by Object.is.
What goes wrong with useShop((s) => ({ lines: s.lines.length })) in Zustand 5?
The selector returns a new object on every call, so the snapshot never looks stable. The run ended in React's update-depth error.
What does useShallow compare?
The fields of the returned object, one by one, so an equal set of values counts as unchanged.
Part 6 · Redux Toolkit, and when it fits
What it adds to the picture
Redux is a store with strict rules. The state is changed only by dispatching actions, and a pure function called a reducer computes the next state from the previous one and the action. Redux Toolkit is the current official way to write it. Its createSlice builds the action creators and the reducer for one feature, and configureStore assembles the store with sensible defaults, including support for async logic and the Redux DevTools browser extension.
The redux.js.org tutorial describes three things worth knowing. A slice's action types are generated from its name and the reducer's key, so added in the cart slice becomes cart/added. Reducers inside createSlice may be written as if they mutate state, because the Immer library turns that code into a new immutable value. And React Redux supplies a Provider, plus the useSelector and useDispatch hooks.
A reducer is a pure function, so you can test it without React.
text
action type: cart/added
quantity after added: 1
quantity after quantitySet: 3
the earlier state still says 1
new state is a new object: true
Real run of the slice's reducer.
The reducer pushed and edited inside the "mutating" code, and yet the earlier state still said quantity 1. Immer recorded the writes against a draft and produced a new object. The action's type came out as cart/added, as described.
Selectors and renders
useSelector runs the selector after every dispatched action and re-renders the component when the result is not equal by ===. A selector that returns a new array every time therefore renders after every action in the whole store. createSelector, from the Reselect library bundled with Redux Toolkit, remembers its last inputs and returns the previous result when they are equal.
tsx
function Fresh() {
renders++
const filled = useSelector((s: RootState) =>
s.cart.lines.filter((l) => l.qty > 0),
)
return <p>{filled.length}</p>
}
function Memoised() {
renders++
const total = useSelector(selectTotal)
return <p>{total}</p>
}
The store combines the cart slice with a second one for prescriptions, and defines one memoised selector.
The test dispatches an action from a different slice, then a real change to a quantity.
text
Fresh warns: Selector unknown returned a different result when called
with the same parameters. This can lead to unnecessary rerenders.
unrelated rx action: Fresh renders 1
unrelated rx action: Memoised renders 0, result function calls since
mount 0
quantity change: Memoised renders 1, result function calls since mount
1
Real run with react-redux 9.3.1. The result function counts its own calls.
React Redux printed a development warning for the selector that returned a new array. The name unknown is the selector function's name, which an anonymous arrow does not have. The react-redux documentation says this check runs in development, calls the selector a second time with the same input on its first call, and is on by default only for that first call. In the run, an unrelated prescription action rendered the unmemoised component, and did not render the memoised one. A quantity change rendered it once and ran the result function once.
Slices belong in the feature folders from the first lesson: the cart slice lives in the cart folder and is exported through its index, and the app folder assembles the store from the feature slices. The tutorial also pre-types the hooks once, as useAppSelector and useAppDispatch, so that components do not repeat the state type on every call.
Choosing between the three
Context and reducer
Zustand
Redux Toolkit
Setup
none beyond React
one create call
store, slices, Provider
Selecting a slice
not with one context, so split it
selector per hook
useSelector per hook
Provider needed
yes
no
yes
Tooling
React DevTools
a devtools middleware ships in the package
Redux DevTools by default
Fits
small, rarely changing state
a few shared client slices
large teams, many features, audit trail of actions
Setup
Context and reducernone beyond React
Zustandone create call
Redux Toolkitstore, slices, Provider
Selecting a slice
Context and reducernot with one context, so split it
Zustandselector per hook
Redux ToolkituseSelector per hook
Provider needed
Context and reduceryes
Zustandno
Redux Toolkityes
Tooling
Context and reducerReact DevTools
Zustanda devtools middleware ships in the package
Redux ToolkitRedux DevTools by default
Fits
Context and reducersmall, rarely changing state
Zustanda few shared client slices
Redux Toolkitlarge teams, many features, audit trail of actions
Pick the smallest tool that works. Context and a reducer carry a lot of apps. A store with selectors is the next step when renders become a problem. Redux Toolkit earns its extra structure when many people change shared state and want every change to be a named, loggable action. None of them replaces a server-state cache for data the server owns.
Check your understanding
Why can a reducer in createSlice look like it mutates state?
Immer gives it a draft and builds a new immutable state from the recorded writes. In the run, the earlier state still had its old quantity.
A component uses useSelector((s) => s.cart.lines.filter(...)) and renders after every action, even ones from another slice. Why, and what fixes it?
filter returns a new array each time, so the === check fails after every action. Wrapping the selector in createSelector returns the previous result while its inputs are equal. In the run, an unrelated action rendered the memoised component 0 times and left the result function at zero new calls.
When does Redux Toolkit pay for its structure?
When many developers change shared state and want each change to be a named action they can log and trace.
Part 7 · Component APIs that scale
Props are an interface
As a pharmacy app grows, shared components such as buttons, selects and cards are used in hundreds of places. Their props become an interface that other code depends on, and changing one prop breaks every caller. A good component API makes wrong use impossible to write and right use obvious.
Four tools do most of the work: composition, discriminated unions, generics and headless hooks.
Making invalid combinations impossible
A button can be a link or an action, never both. Listing optional href and optional onClick props lets a caller pass neither or both. A discriminated union says exactly what is allowed: either an href with no onClick, or an onClick with no href.
tsx
type Common = { children: ReactNode; tone?: 'primary' | 'quiet' }
type LinkButton = Common & { href: string; onClick?: never }
type ActionButton = Common & { onClick: () => void; href?: never }
exportfunction Button(props: LinkButton | ActionButton) {
if (props.href !== undefined) {
return <a href={props.href}>{props.children}</a>
}
return <button onClick={props.onClick}>{props.children}</button>
}
A generic component lets one definition work for any option type while keeping the types connected. In the select below, whatever type options holds is also the type of value, of the argument to getLabel and of the argument to onChange.
The file below contains four mistakes. TypeScript 7.0.2 reports each.
tsx
import { Button, Card, Select } from'./parts'exportconst a = (
<Button href="/cart" onClick={() => {}}>
Cart
</Button>
)
exportconst b = <Button>Nothing to do</Button>
exportconst c = (
<Select
options={['Strip', 'Bottle']}
value="Strip"
getLabel={(o) => o}
onChange={(o: number) => console.log(o)}
/>
)
exportconst d = <Card>no header</Card>
text
ar/api/bad.tsx(4,4): error TS2322: Type '{ href: string; onClick: ()
=> void; children: string; }' is not assignable to type
'IntrinsicAttributes & (ActionButton | LinkButton)'.
Types of property 'onClick' are incompatible.
Type '() => void' is not assignable to type 'undefined'.
ar/api/bad.tsx(9,19): error TS2322: Type '{ children: string; }' is
not assignable to type 'IntrinsicAttributes & (ActionButton |
LinkButton)'.
Property 'onClick' is missing in type '{ children: string; }' but
required in type '{ onClick: () => void; href?: undefined; }'.
ar/api/bad.tsx(13,15): error TS2322: Type 'string' is not assignable
to type 'number'.
ar/api/bad.tsx(13,24): error TS2322: Type 'string' is not assignable
to type 'number'.
ar/api/bad.tsx(14,5): error TS2322: Type 'string' is not assignable to
type 'number'.
ar/api/bad.tsx(15,22): error TS2322: Type 'number' is not assignable
to type 'string'.
ar/api/bad.tsx(20,19): error TS2741: Property 'header' is missing in
type '{ children: string; }' but required in type 'CardProps'.
Real output of `tsc --noEmit`. Long lines are wrapped to fit.
The first error says a link button cannot have an onClick. The second says a button with neither prop is missing one. The generic example is the instructive one. Because onChange was typed with a number, TypeScript chose number for the connected type and reported the strings, in three places. One wrong annotation shows up wherever the types disagree. The last error is a missing required header.
Slots and headless hooks
Props that accept JSX are called slots. A Card with required header and optional footer slots lets callers place anything there, and a missing header is a compile error, as the last mistake showed.
A headless hook holds behaviour with no markup. The one below owns the open state and the wiring between a toggle button and its panel. It returns props objects for the caller to spread, so each screen supplies its own elements and styles.
function Faq() {
const d = useDisclosure()
return (
<>
<button {...d.buttonProps} onClick={d.toggle}>
Returns policy
</button>
<p {...d.panelProps}>Unopened packs can be returned.</p>
</>
)
}
text
<a href="/cart">Cart</a>
<button>Pay</button>
<select>
<option value="0">Strip of 10</option>
<option value="1">Bottle of 60</option>
</select>
<section>
<header>Order</header>3 items</section>
<button aria-expanded="false" aria-controls="_r_0_">Returns
policy</button>
<p id="_r_0_" hidden="">Unopened packs can be returned.</p>
Real run. The first lines are the earlier components' HTML.
The disclosure's button and panel came out linked by the same generated id, and the panel was hidden. The useId value looks like _r_0_ in React 19.3. The same hook could drive an accordion, a menu or a filter drawer, because it makes no choice about markup.
Slots are one answer to the question of how much a component should decide. A component that decides everything needs many props to be reused. A component that decides nothing is just a wrapper. Passing a function as a prop, such as getLabel, gives the caller control over one decision, how an option is shown, while the component keeps control of the behaviour around it. Choose the decisions to hand over by asking what callers have actually needed to change, and keep the rest inside.
Keeping an API small
Every prop is a promise. Before adding one, check whether composition covers it: a slot, a children function or a second small component. Prefer a few well-typed props to many flags, and give each component one job. An API that is hard to misuse is cheaper to maintain than one that is thoroughly documented.
Check your understanding
Why does the discriminated Button reject href together with onClick?
The link variant declares onClick?: never, so no value can be assigned to it. The compiler reported that () => void is not assignable to undefined.
What does the generic Select<T> connect?
The type of options, value, the argument of getLabel and the argument of onChange. A wrong type in one place surfaces in the others, as the three errors on the strings showed.
What is a headless hook?
A hook that owns behaviour and state and returns props to spread, but renders no markup, so each screen can supply its own elements.