Courses / React 19: From Components to Production / Chapter 27
Module 11 · Advanced Component Patterns · Chapter 27 of 30
State Reducer: Letting Callers Change How State Updates
Builds on Control Props: Components That Work Controlled or Uncontrolled and State Initializer: Initial Values and Reset. Next up: Machine Coding Practice: Timed UI Builds.
Part 1 · The problem: one transition has to behave differently
A rule the component does not have
The exam-results FAQ is an accordion, and a product owner asks for one change: at least one answer must always stay open, so the page is never a column of closed headers. The accordion cannot do that, because it toggles whatever you click.
The hook owns its transitions, the rules that turn one state into the next: clicking an open item closes it, clicking a closed one opens it. A caller can read the state and set it from outside, but it cannot change a rule. When the rule is wrong for one page, the options are poor. Fork the component, add a prop for this one case, or take over the state.
The last option is available because of the control props chapter. The test below runs the plain accordion, and then an accordion whose caller owns openItems and ignores any change that would leave the list empty.
function Workaround() { const [open, setOpen] = useState(['results']) return ( <Accordion openItems={open} onOpenItemsChange={(next) => next.length > 0 && setOpen(next)} > <Items /> </Accordion> ) }
plain accordion: open = results close the last open item: open = none caller owns the state: open = results close the last open item: open = results
Output of a real run, React 19.3.1, StrictMode off.