Courses / React 19: From Components to Production / Chapter 23
Module 11 · Advanced Component Patterns · Chapter 23 of 30
Control Props: Components That Work Controlled or Uncontrolled
Builds on State and Effects: useState, Events, useEffect and Cleanup and Compound Components: Parts That Share State Through Context. Next up: Props Collections: Bundling the Props an Element Needs.
Part 1 · Controlled and uncontrolled components
Who owns the state
The exam-results FAQ page needs an Expand all button above the accordion, and the accordion from the previous chapter cannot be driven from outside. This chapter adds control props so the same component works with its own state or with state owned by its parent.
A form input already works both ways. With value and onChange the input is controlled: the parent owns the text and the input shows whatever it is given. With defaultValue it is uncontrolled: the input keeps its own text and the parent only gives it a starting point. The same split applies to any component with state. An uncontrolled accordion keeps its open list inside and starts from defaultOpenItems. A controlled accordion shows the openItems its parent passes and asks the parent to change them through onOpenItemsChange. The pattern that lets one component offer both is called control props.
Downshift, a library for comboboxes and menus, uses the same idea. Its README lists isOpen, selectedItem, inputValue and highlightedIndex as pieces of state you can pass as props when you need more control, and describes an onStateChange handler that runs whenever the internal state changes.
What the previous accordion cannot do
The accordion from the previous chapter is uncontrolled only. A page that wants to open everything has no prop to do it with. The obvious attempt is to change defaultOpenItems after the first render, so a test tried it.
before false,false,false after changing defaultOpenItems to all three false,false,false
Real run in jsdom with the previous chapter's accordion.
Nothing happened. A default is read once, when the component mounts, exactly as defaultValue is for an input. The usual workaround is to change the component's key, which throws away the whole accordion and its state and remounts it, a blunt tool for a button click.
The parent in control
The page below owns the list and passes it down with a handler. This is the controlled form. A test clicked Open all and then closed one question with its header.
function Controlled() { const [open, setOpen] = useState<string[]>([]) log.push('Page') return ( <> <button onClick={() => setOpen(ids)}>Open all</button> <Accordion openItems={open} onOpenItemsChange={setOpen}> <Items A={Accordion} /> </Accordion> </> ) }
The controlled page. The Accordion takes openItems and onOpenItemsChange.
controlled, Open all: true,true,true | renders: Page, Accordion,
Item marksheet, Header marksheet, Panel marksheet, Item reval,
Header reval, Panel reval, Item supply, Header supply,
Panel supply
controlled, click header: true,false,true | renders: Page,
Accordion, Item marksheet, Header marksheet, Panel marksheet,
Item reval, Header reval, Panel reval, Item supply,
Header supply, Panel supplyReal run in jsdom: the three expanded flags, then what rendered.
Open all opened all three, and a header click closed the second one. In both cases the click on the header did not change the accordion's state directly. It called onOpenItemsChange with the list the user asked for, the page stored it, and the accordion rendered from the new prop. That round trip is what controlled means.
Choosing a mode
There are three ways to run the accordion, and the choice is the caller's. The previous chapter's callback gives a middle form: uncontrolled, but with onOpenItemsChange so the parent can watch.
| Uncontrolled | Uncontrolled with a callback | Controlled | |
|---|---|---|---|
| Who stores the list | the accordion | the accordion | the parent |
| Parent can read it | no | yes, through the callback | yes, it holds it |
| Parent can set it after mount | no | no | yes |
| Parent must supply a handler | no | no | yes |
Uncontrolledthe accordion
Uncontrolled with a callbackthe accordion
Controlledthe parent
Uncontrolledno
Uncontrolled with a callbackyes, through the callback
Controlledyes, it holds it
Part 2 · Implementing control props
One hook for the rule
The rule for a component that offers both modes fits in a few lines. If the parent passes a value, that value is the state. If not, the component keeps its own. When something asks for a change, call the parent's onChange with the new value, and update the internal state only in the uncontrolled case. Each stateful component could repeat this. Instead the lab wrote it once as a hook, useControllableState.
export function useControllableState<T>({ value, defaultValue, onChange, readOnly, }: Options<T>) { const [inner, setInner] = useState(defaultValue) const controlled = value !== undefined const current = controlled ? value : inner
The first part of the hook: which mode applies.
The mode is decided by one test, value !== undefined. An undefined value means the parent did not pass the prop. That is also why a controlled value cannot be undefined. A null does not count as missing: the test is strict, so null would be treated as a controlled value, which is a different choice from React's own input, where the react.dev page says null and undefined both have to be replaced by an empty string.
The second part is the function that requests a change. It needs the latest value and the latest onChange without changing its own identity on every render, so it reads them from a ref that an effect keeps current. The previous chapter used the same trick for the change callback.
const latest = useRef({ current, controlled, onChange, readOnly }) useEffect(() => { latest.current = { current, controlled, onChange, readOnly } }) const set = useCallback((update: T | ((cur: T) => T)) => { const { current: cur, controlled: isControlled, onChange: notify, readOnly: locked, } = latest.current if (locked) return const next = typeof update === 'function' ? (update as (c: T) => T)(cur) : update if (!isControlled) { latest.current = { ...latest.current, current: next } setInner(next) } notify?.(next) }, []) return [current, set] as const
The setter. It accepts a value or an updater, like useState.
The setter accepts a value or a function, as useState does, and computes the next value from the latest one. In the uncontrolled case it also writes the ref, so two calls in one event compose. In the controlled case it does not: the parent may refuse the change, and the ref must keep matching the prop the parent actually passed. Then it calls onChange in both cases. With readOnly set, the setter returns before doing anything.
The accordion on top of it
The accordion's root now takes openItems as well as defaultOpenItems, and hands both to the hook.
const [openItems, setOpenItems] = useControllableState({ value: openProp, defaultValue: defaultOpenItems, onChange: onOpenItemsChange, readOnly, }) const toggleItem = useCallback( (value: string) => setOpenItems((cur) => cur.includes(value) ? cur.filter((v) => v !== value) : [...cur, value], ), [setOpenItems], )
The root of the accordion with control props.
Everything below the root, the contexts, the memoised values and the parts, stayed as it was. The toggle still asks for the next list through an updater, and the hook decides who stores it.
A toggle on the same hook
The same hook can power a single-question toggle. useToggle takes on and onChange for control, and initialOn for the uncontrolled start.
export function useToggle(options: ToggleOptions = {}) { const { initialOn = false, on, onChange, readOnly } = options const [value, setOn] = useControllableState({ value: on, defaultValue: initialOn, onChange, readOnly, }) const toggle = useCallback(() => setOn((cur) => !cur), [setOn]) return { on: value, toggle, setOn } }
useToggle on top of useControllableState.
A small FaqItem component passes its props straight to useToggle, so a test could use it in both modes.
export function FaqItem(props: ToggleOptions) { const { on, toggle } = useToggle(props) return ( <> <button type="button" aria-expanded={on} onClick={toggle}> Revaluation? </button> {on && <p>Rs 500 per paper.</p>} </> ) }
One component, two modes.
uncontrolled, start: true uncontrolled, after click: false onChange saw [false] controlled, parent opened it: true onChange saw [] controlled, header clicked: false onChange saw [false]
Real run in jsdom. The first two lines are uncontrolled, the last two controlled.
The uncontrolled item started open because of initialOn, closed on a click and reported the change. The controlled item was opened by a button in the parent, which called its own setter, and onChange stayed silent: it reports changes that the component asks for, not changes the parent makes. A header click then asked to close it and onChange saw false.
Controlled and uncontrolled differ in who stores the value, and the component's markup is the same in both. Control props keep the choice with the caller.
The picture shows what renders in each mode when question b is opened. It uses a small tree of the same shape.
Two calls in one event
The two modes differ in one more way. A test called the setter twice in one click, each time with an updater that appends a letter, once uncontrolled and once with a parent that stores each value it receives.
uncontrolled: callback saw [["a"],["a","b"]] | shown go ab controlled: callback saw [["a"],["b"]] | shown go b
Real run in jsdom: set(c => [...c, 'a']) then set(c => [...c, 'b']) in one click.
Uncontrolled, the second call started from the first call's result. Controlled, both calls started from the list the parent had last passed, so the second request was ["b"] and the parent stored that. This follows from the rule that the parent decides: until the parent passes a new list, the component's value has not changed. A controlled form input behaves the same way if two handlers each call setValue(value + ...) with the same stale value. When one event needs several changes, build the final list in one call.
Why does the setter write its ref only in the uncontrolled case?
- In controlled mode the parent decides the value. If the parent refuses a change, the ref must still match the prop, not the request.
What did onChange report when the parent opened the controlled item through its own button?
- Nothing. The run's list stayed empty.
onChangereports changes the component requests, not changes the parent makes.
How does the hook decide which mode applies?
value !== undefined. An undefined value means the prop was not passed, so the component uses its own state.
Part 3 · Guarding against mode switches
The same warning React gives inputs
Nothing stops a parent from passing openItems on one render and undefined on the next. Then the component changes mode in the middle of its life: state that the parent owned a moment ago is now whatever the accordion held internally, and the user sees the list jump. React treats the same slip on an input as a bug and warns about it. A test printed the real warning for an input whose value changes from a string to undefined.
A component is changing a controlled input to be uncontrolled.
This is likely caused by the value changing from a defined to
undefined, which should not happen. Decide between using a
controlled or uncontrolled input element for the lifetime of
the component. More info:
https://react.dev/link/controlled-componentsReal run in jsdom: React's own warning for an input. Long lines are wrapped to fit.
The message names the cause, says it should not happen and tells the developer what to decide. A component with control props deserves the same courtesy. A common source is a parent whose state starts as undefined while data loads, then becomes a list.
A development-only warning
The hook remembers which mode it started in and compares on every change. The check is an effect that runs when the mode flag changes and reports only outside production builds. It gives the message in plain words.
const wasControlled = useRef(controlled) useEffect(() => { if (process.env.NODE_ENV === 'production') return if (wasControlled.current !== controlled) { const from = wasControlled.current ? 'controlled' : 'uncontrolled' const to = controlled ? 'controlled' : 'uncontrolled' console.error( `A component is changing from ${from} to ${to}. ` + 'Pick one mode for the lifetime of the component.', ) } wasControlled.current = controlled }, [controlled])
The mode-switch warning inside useControllableState.
The test gave the accordion openItems equal to a list, then a button set the parent's state to undefined.
A component is changing from controlled to uncontrolled. Pick one
mode for the lifetime of the component.Real run in jsdom: the accordion's warning after the parent's state became undefined.
The warning fired once, at the moment of the change. After it the accordion fell back to its own internal list, which started from defaultOpenItems and so was empty.
Two points about the check. It runs in an effect after the render, so the page has already shown the jump by the time the console shows the message; it is a tool for the developer, and the real fix is in the parent. And it is guarded by process.env.NODE_ENV, the usual way libraries keep development checks out of production builds. This chapter did not inspect a production bundle for it.
A parent that loads its list
The most common cause is data that arrives late. A page fetches the list of open items, perhaps from the user's saved preferences, and keeps it in state. Until the answer arrives the state is undefined, and then it becomes a list. A test ran both ways, with the list arriving after 20 ms.
starts undefined: 1 warning(s) [ 'A component is changing from uncontrolled to controlled. Pick one mode for the lifetime of the component.' ] starts as an empty list: 0 warning(s) []
Real run in jsdom. The state either starts undefined or starts as an empty list, then becomes ['notice']. Long lines are wrapped to fit.
Starting as undefined made the accordion uncontrolled for 20 ms and then controlled, and the hook said so. Starting with an empty list kept it controlled from the first render, and the list simply changed. A parent can avoid the whole problem by never passing undefined for a controlled prop. The react.dev input page gives the same advice for inputs: start the state as an empty string, or pass value={someValue ?? ''}. For a list that reads openItems={saved ?? []}. Give the state a real initial value, an empty list, and keep the prop defined for the component's life. If the parent genuinely wants to switch modes, it should change the component's key so that React mounts a new instance in the new mode. A test did that: an uncontrolled accordion was opened by a click, then the page switched to a controlled one with an empty list and a different key.
uncontrolled after a click: true
controlled with a new key: false | warnings: 0Real run in jsdom.
The new instance started from the parent's list, closed, and no warning appeared. The old instance's state was discarded along with it, which is the cost of the approach.
What triggers the mode-switch warning in the hook?
- The
controlledflag differing from its value on the previous render, for exampleopenItemsgoing from a list toundefined.
Why is the check an effect and not part of the render?
- It compares across renders using a ref, and effects are the place to run side effects such as logging. It reports after the render, so it informs the developer and does not prevent the jump.
Part 4 · Read-only and partial control
A value without a handler
A controlled component with no way to change its value is read-only. That is sometimes the intention, such as a published FAQ whose open items are fixed by the page, and often a mistake, such as forgetting to wire the handler. React warns about the second case for inputs. A test printed the real text for <input value="a" />.
You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.
Real run in jsdom: React's warning for an input with value and no onChange. Long lines are wrapped to fit.
The last sentence is the pattern: if the lock is deliberate, say so with readOnly. The hook copies that.
const hasHandler = onChange !== undefined useEffect(() => { if (process.env.NODE_ENV === 'production') return if (controlled && !hasHandler && !readOnly) { console.error( 'A value was provided without an onChange handler. ' + 'Add onChange, or set readOnly to make the lock deliberate.', ) } }, [controlled, hasHandler, readOnly])
The missing-handler warning, and where readOnly silences it.
A test gave the accordion an open item in openItems with no handler, clicked the header to close it, and then re-rendered with readOnly.
after a click, aria-expanded = true
A value was provided without an onChange handler. Add onChange, or
set readOnly to make the lock deliberate.
with readOnly, new warnings: 0
readOnly: handler calls after a click: 0Real run in jsdom.
The item stayed open, so the click changed nothing, and the console explained why. With readOnly the warning did not appear, and a click no longer called the handler: the hook's setter returns early, so nothing is requested.
A subtle case is a parent that supplies a handler but ignores it. The setter does not change the ref in controlled mode, so each click asks for the same thing. A test clicked a closed item twice with a parent that never updated its list.
parent ignores both requests; handler saw [["a"],["a"]]
Real run in jsdom: what the handler received on each click.
Four cases side by side
The runs in this lesson cover the combinations a parent can create with a list.
| Parent passes | Click on a header | Warning |
|---|---|---|
| list, no handler | nothing changes | yes |
list and readOnly | nothing changes, handler never called | no |
| list and a handler that ignores the change | handler called with the request, nothing changes | no |
| list and a handler that edits the change | the edited list is shown | no |
Only the first row is a mistake. The other three are decisions, and each states the decision in a way a reader of the page can see.
A parent that answers late
A controlled component renders what it is given, so a parent that answers slowly makes the interface slow. This happens when the parent checks something with a server before accepting a change. A test gave the accordion a parent that sets its list 40 ms after the request.
right after the click: false after the parent answered: true
Real run in jsdom.
For those 40 ms the header looked unresponsive. If that is not acceptable, the parent can update its state at once and undo it when the server refuses, or the component can be left uncontrolled and report changes through the callback. Control props give the choice and leave the trade-off to the caller.
Controlling one item of many
The parent's handler can also refuse part of a change. Suppose the first FAQ item is a notice that must always stay open. The page keeps the list and re-adds the notice whenever a change would remove it. The notice's header also passes aria-disabled through its rest props, which the APG accordion page suggests for a button whose panel the accordion does not let you collapse.
<Accordion
openItems={open}
onOpenItemsChange={(next) =>
setOpen(next.includes('notice') ? next : [...next, 'notice'])
}
>
{['notice', 'reval'].map((v) => (
<Accordion.Item key={v} value={v}>
<Accordion.Header aria-disabled={v === 'notice' || undefined}>
{v}
</Accordion.Header>
<Accordion.Panel>x</Accordion.Panel>
</Accordion.Item>
))}
</Accordion>The page: one item the parent will not let close.
start: notice=true reval=false click notice: notice=true reval=false click reval: notice=true reval=true click reval again: notice=true reval=false notice header aria-disabled = true
Real run in jsdom.
Clicking the notice changed nothing. The other item opened and closed as normal. This is partial control: the accordion owns the mechanics, and the parent owns one rule about the list. It needed no new prop, only the handler that control props already provide.
What should a component do when it gets value and no onChange?
- Warn, unless the caller marked it
readOnly. In the run the warning appeared once, andreadOnlysilenced it.
A parent never updates its list. What does the accordion's handler receive on repeated clicks?
- The same request each time. The run's handler saw
["a"]twice.
How did the page keep the notice open?
- Its
onOpenItemsChangere-addednoticeto any list that lacked it, so the controlled list never lost it.
Part 5 · Typing control props
Making wrong combinations unwritable
The warnings catch mistakes at run time. Types can catch them before the code runs. The wrong combinations are easy to list. on without onChange is a read-only value that nobody marked. readOnly without on has nothing to lock. initialOn together with on names two sources of truth, and onChange with readOnly names a handler that can never run. A union of three shapes describes what is allowed.
type Uncontrolled = { initialOn?: boolean on?: undefined onChange?: (on: boolean) => void readOnly?: undefined } type Controlled = { on: boolean onChange: (on: boolean) => void initialOn?: undefined readOnly?: undefined } type Locked = { on: boolean readOnly: true onChange?: undefined initialOn?: undefined } export type ToggleOptions = Uncontrolled | Controlled | Locked
Three allowed shapes, then their union.
Each shape sets the props it forbids to undefined, so a caller who passes one gets an error. Uncontrolled allows initialOn and an optional onChange. Controlled requires on and onChange. Locked requires on and readOnly. The hook and the component both take ToggleOptions. Function overloads can express the same idea for a function with several call shapes; for props that arrive as one object, a union is the simpler tool.
What the compiler says
A file that uses the component correctly in five ways compiled without comment under TypeScript 7.0.2. A second file uses it incorrectly in four ways, and the compiler reported each one.
export const a = <FaqItem on={true} /> export const b = <FaqItem initialOn on={false} onChange={() => {}} /> export const c = <FaqItem readOnly /> export const d = <FaqItem on={true} readOnly onChange={() => {}} />
The four mistakes.
bad.tsx(3,19): error TS2322: Type '{ on: true; }' is not assignable to type 'IntrinsicAttributes & ToggleOptions'. Type '{ on: true; }' is not assignable to type '(IntrinsicAttributes & Controlled) | (IntrinsicAttributes & Locked)'. Property 'readOnly' is missing in type '{ on: true; }' but required in type 'Locked'. bad.tsx(5,19): error TS2322: Type '{ initialOn: true; on: boolean; onChange: () => void; }' is not assignable to type 'IntrinsicAttributes & ToggleOptions'. Types of property 'on' are incompatible. Type 'boolean' is not assignable to type 'undefined'. bad.tsx(7,19): error TS2322: Type '{ readOnly: true; }' is not assignable to type 'IntrinsicAttributes & ToggleOptions'. Property 'on' is missing in type '{ readOnly: true; }' but required in type 'Locked'. bad.tsx(9,19): error TS2322: Type '{ on: true; readOnly: true; onChange: () => void; }' is not assignable to type 'IntrinsicAttributes & ToggleOptions'. Types of property 'onChange' are incompatible. Type '() => void' is not assignable to type 'undefined'.
Real output of `tsc --noEmit`, with the folder shortened. Long lines are wrapped to fit.
Each message points at the exact prop. For on alone, TypeScript picks the closest shape in the union and says what that shape is missing: readOnly. The second error says on cannot be a boolean because the shape that allows initialOn forbids it. The fourth says onChange cannot coexist with readOnly.
The same union on the accordion
The accordion's root props follow the same three shapes, written with openItems, defaultOpenItems and onOpenItemsChange.
type Uncontrolled = { defaultOpenItems?: string[] onOpenItemsChange?: (openItems: string[]) => void openItems?: undefined readOnly?: undefined } type Controlled = { openItems: string[] onOpenItemsChange: (openItems: string[]) => void defaultOpenItems?: undefined readOnly?: undefined } type Locked = { openItems: string[] readOnly: true onOpenItemsChange?: undefined defaultOpenItems?: undefined } type RootProps = { children: ReactNode } & ( Uncontrolled | Controlled | Locked )
The root's props, three shapes in a union.
The test that deliberately passes openItems with no handler, and readOnly with a handler, carries a @ts-expect-error comment on each of those lines. The compiler treats an unused directive as an error, so the comments prove that the types really reject those calls. Two more mistakes went into a file of their own.
export const a = ( <Accordion openItems={['notice']}> <Accordion.Item value="notice"> <Accordion.Header>Notice</Accordion.Header> <Accordion.Panel>Read this first.</Accordion.Panel> </Accordion.Item> </Accordion> ) export const b = ( <Accordion defaultOpenItems={['notice']} openItems={['notice']} onOpenItemsChange={() => {}} > {null} </Accordion> )
Two mistakes on the accordion.
bad-accordion.tsx(4,4): error TS2322: Type '{ openItems: string[]; children: Element; }' is not assignable to type 'IntrinsicAttributes & RootProps'. Type '{ openItems: string[]; children: Element; }' is not assignable to type '(IntrinsicAttributes & { children: ReactNode; } & Controlled) | (IntrinsicAttributes & { children: ReactNode; } & Locked)'. Property 'readOnly' is missing in type '{ openItems: string[]; children: Element; }' but required in type 'Locked'. bad-accordion.tsx(13,4): error TS2322: Type '{ defaultOpenItems: string[]; openItems: string[]; onOpenItemsChange: () => void; children: null; }' is not assignable to type 'IntrinsicAttributes & RootProps'. Types of property 'openItems' are incompatible. Type 'string[]' is not assignable to type 'undefined'.
Real output of `tsc --noEmit`, with the folder shortened. Long lines are wrapped to fit.
The first mistake is a list with no handler, rejected the same way as the toggle. The second names a default and a controlled value together, which the uncontrolled shape forbids by typing openItems as undefined.
Typing the hook itself
The hook is generic, so the types of value, defaultValue and the setter's argument must agree. A short file gave it a string value with a number default, and called a list's setter with a number.
const [mixed] = useControllableState({ value: 'a', defaultValue: 1 }) const [ok, setOk] = useControllableState({ value: undefined, defaultValue: ['a'], }) setOk(['b']) setOk(3)
Two mistakes with the hook, and the compiler's answers.
bad-hook.tsx(4,54): error TS2322: Type 'number' is not assignable to type 'string'. bad-hook.tsx(10,9): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string[] | ((cur: string[]) => string[])'.
Real output of `tsc --noEmit`, folder shortened. Long lines are wrapped to fit.
The first error points at the number: TypeScript settled on string for the type parameter and rejected the other. The second shows that the setter accepts a list or an updater function and nothing else. The valid calls, including value: undefined with a list default, passed.
Types and run-time warnings cover different ground. Types stop a caller who writes the wrong props in code. The warnings catch a prop that changes over time, such as undefined arriving from a data load, which no type can see. Use both.
Why does passing only on fail to compile?
- The shapes that allow
onneed eitheronChangeorreadOnly. The compiler reported thatreadOnlywas missing from the closest shape.
Which mistake can a type check never catch?
- A prop that changes at run time, such as a controlled value that becomes
undefinedafter a load. The run-time warning covers that.
What does setting a forbidden prop to undefined in a union member do?
- It makes the compiler reject any caller who passes that prop with that shape. The run's
initialOnwithonwas rejected.
All chapters · Previous: Compound Components: Parts That Share State Through Context