Courses / React 19: From Components to Production / Chapter 26
Module 11 · Advanced Component Patterns · Chapter 26 of 30
State Initializer: Initial Values and Reset
Builds on Control Props: Components That Work Controlled or Uncontrolled, Prop Getters: Merging Caller Props With Component Behaviour and Suspense, Streaming SSR and Code-Splitting. Next up: State Reducer: Letting Callers Change How State Updates.
Part 1 · Initial value, not controlled value: initialOn is read once
Two ways to hand a component a value
A FAQ item on the exam-results page can start open or closed. The caller can say so in two different ways, and they mean different things, so a hook that mixes them up surprises people.
A controlled value, on, is state that the caller owns. Every render, the component shows what the caller says, and the caller changes it in response to onChange. The control props chapter built that, and its useToggle takes on, onChange and readOnly for control. The copy in this chapter keeps only what the lesson needs: it leaves out the control props, the prop collections and the getters of earlier chapters. An initial value, initialOn, is only a starting point. The component reads it once when it mounts, keeps its own state from then on, and ignores later changes to the prop.
The names carry the difference. React's own inputs follow it: an input with defaultValue starts with that text and is then the user's, and an input with value is the caller's. React's reference for useState states the same rule for state: its argument is the value you want the state to be initially, and "this argument is ignored after the initial render".
| Prop | Read | After mount | Who owns the state |
|---|---|---|---|
on | every render | follows the caller | the caller |
initialOn | once, at mount | ignored | the component |
onA prop that changes after mount, run
The hook takes initialOn and starts a useReducer from it. A page component keeps its own open state, passes it down as initialOn, and has a button that sets it to true after the item has mounted. The test logs every render of the item and reads aria-expanded after each step.
function FaqItem(props: { initialOn: boolean }) { const { on, toggle } = useToggle({ initialOn: props.initialOn }) lines.push(`FaqItem render: initialOn=${props.initialOn}, on=${on}`) return ( <section> <button aria-expanded={on} onClick={toggle}> Revaluation fee </button> </section> ) }
function Page() { const [open, setOpen] = useState(false) return ( <> <button onClick={() => setOpen(true)}>Open from the page</button> <FaqItem initialOn={open} /> </> ) }
FaqItem render: initialOn=false, on=false mounted: aria-expanded=false FaqItem render: initialOn=true, on=false page set initialOn to true: aria-expanded=false FaqItem render: initialOn=true, on=true user clicked: aria-expanded=true
Output of a real run, React 19.3.1, StrictMode off.
The item rendered with initialOn=true and on=false. The prop had changed, the component had rendered again because its parent did, and its own state was untouched. The button still said aria-expanded=false. Only the user's click changed it.
This is the behaviour the name promises, and it is easy to forget. A developer who sets initialOn from data that arrives late, such as a saved setting fetched after the first render, sees nothing happen. The fix is not to make the hook follow the prop. It is to wait to render the item until the data is there, or to give the item a key, which makes React build a new item.
What the render tree shows
Watch for the item rendering with a new initialOn and its state not moving
Read it as steps
The prop moves, the state stays
The scene replays the run. The page's state moves first, and the item renders because its parent did. Its on stays false, and nothing reaches the DOM. Then the click changes the item's own state and one render follows, with one DOM change.
The item's render is cheap, so the lesson is not about cost. It is about which of two values the component trusts. A prop named initialOn is a promise that the component will not listen to later changes, and a hook that listens anyway breaks the promise for every caller that relied on it.
Why not follow the prop
A hook could copy the prop into state whenever it changes, with an effect. That makes the component half controlled: it has state of its own and also obeys the prop, so the caller can never tell which one is in charge. If the caller sets initialOn to true while the user has just closed the item, the item opens again under the user's finger.
The two honest designs are the ones in the table above. Use on and onChange when the caller should own the value. Use initialOn when the component should own it. A component that supports both, as the control props chapter's hook does, chooses by whether on is given, and the initial value then plays no part.
Name the prop so the choice is visible at the call site. initialOn and defaultOpenItems both tell the reader that the value is read once. Plain on would suggest that it is live.
In the run, the page set initialOn to true after the item had mounted. What did the item show, and why?
- It still showed
aria-expanded=false. The hook readinitialOnonce at mount, and the later prop change was ignored.
What is the difference between on and initialOn?
onis controlled: the caller owns the value and the component follows it every render.initialOnis the starting value only: the component owns the state afterwards.
A developer fetches a saved setting and passes it as initialOn once it arrives. Why does the item not change?
- The item mounted before the data arrived and read the old value. Later changes to
initialOnare ignored, so render the item after the data is ready, or give it akey.
Part 2 · Lazy initialisation: reading a saved value once
An initial value that is expensive or stored
A reader who opens the revaluation question on the portal may want it to stay open the next time. The hook can read that preference from localStorage when it starts. Reading storage is cheap, but parsing JSON and doing it on every render is wasted work, and for a heavier initial value it would be worse.
useState lets you pass either a value or a function. A function is called lazily: React calls it during the first render only and keeps the result. The React reference makes the difference explicit. Passing createInitialTodos() calls the function on every render even though only the first result is used. Passing createInitialTodos, the function itself, calls it during initialisation only.
export function readSaved(): boolean { counter.calls++ const raw = localStorage.getItem(KEY) return raw === null ? false : JSON.parse(raw).on === true }
function Eager() { const [on] = useState(readSaved()) const [, bump] = useState(0) return ( <button onClick={() => bump((n) => n + 1)}>{String(on)}</button> ) }
function Lazy() { const [on] = useState(readSaved) const [, bump] = useState(0) return ( <button onClick={() => bump((n) => n + 1)}>{String(on)}</button> ) }
The two components differ by two characters. useState(readSaved()) runs the reader on every render and throws the result away after the first. useState(readSaved) hands React the function.
Counting the calls
readSaved counts its own calls. The test stores { "on": true }, mounts each component, clicks its button twice to force two more renders, and prints the count. The third component starts a useReducer with the init argument, the function that useReducer takes as its third parameter and calls with initialArg to build the first state. Then the same three run under StrictMode.
plain useState(readSaved()): shows true, calls after mount 1, after two more renders 3 plain useState(readSaved): shows true, calls after mount 1, after two more renders 1 plain useReducer init: shows true, calls after mount 1, after two more renders 1 StrictMode useState(readSaved()): shows true, calls after mount 2, after two more renders 6 StrictMode useState(readSaved): shows true, calls after mount 2, after two more renders 2 StrictMode useReducer init: shows true, calls after mount 2, after two more renders 2
Output of a real run. Long lines are wrapped for the page.
Without StrictMode, the eager call read storage once on mount and twice more on the two re-renders: 3 calls. The lazy useState and the useReducer init each read once and stayed at 1. All three showed true, so the saved value reached the state.
With StrictMode, every count doubled on mount. React calls initialiser functions twice in development to help find impure ones, and uses the result of one call. The React references for useState and useReducer say this is development-only. The eager version then reached 6 calls after two more renders, and the lazy ones stayed at 2.
A pure initialiser is unaffected by the double call. One that increments a counter or writes to storage is not, and the second call is how you find out.
A saved value that cannot be trusted
Storage holds whatever was put in it, by an older version of the page, by another tab or by the user. A reader that assumes valid JSON can crash the whole component on mount. The first test stores {bad and renders the lazy component inside an error boundary. The second renders the same storage through a reader that checks and falls back.
unguarded: SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2) safe: on=false
Output of a real run.
The unguarded component never rendered: the error from JSON.parse reached the boundary. The safe reader wrapped the read in try and returned the default, so the item rendered closed. An initialiser runs during render, so an exception in it is a render error.
The reader has another environment to survive. On a server there is no localStorage. The test below runs the same two readers in Node with renderToString.
typeof localStorage: undefined unguarded: ReferenceError: localStorage is not defined guarded: <p>false</p>
Output of a real run, vitest environment `node`.
In Node, typeof localStorage was undefined, and the unguarded reader threw a ReferenceError. The guarded one returned false. That guard has a price: the server renders closed, and a client with a saved true would render open on its first pass. A first client render that differs from the server's HTML is a hydration mismatch, which the suspense chapter showed. Reading storage in an effect after mount avoids the mismatch, at the cost of one extra render.
In the run without StrictMode, how many times did useState(readSaved()) call the reader after mount and two re-renders, and how many did useState(readSaved)?
- 3 and 1. The eager form calls the function on every render, and the lazy form only during initialisation.
Why did the counts double on mount under StrictMode?
- In development React calls initialiser functions twice to help find impurities, and keeps the result of one. It is development-only.
Part 3 · Reset to the initial value: which initial value?
What reset should mean
A "show all answers again" button on the results FAQ should put every item back as it started. The hook needs a reset function, and the first question is what "as it started" means. There are two plausible answers when the caller's initialOn has changed since mount.
- The first value. The one the component actually started with. It matches how
useStatetreats its argument. - The latest value. Whatever
initialOnis right now. It lets the caller change what reset means.
The reducer makes the choice explicit. The reset action carries the value to go back to, so the reducer stays pure and knows nothing about props.
export function toggleReducer( state: ToggleState, action: ToggleAction, ): ToggleState { switch (action.type) { case toggleActionTypes.toggle: return { on: !state.on } case toggleActionTypes.set: return { on: action.on } case toggleActionTypes.reset: return { on: action.initialOn } } }
The hook decides what to put in the action. For the first value it keeps the mount value in a ref and reads it when reset runs.
export function useToggle({ initialOn = false } = {}) { const [{ on }, dispatch] = useReducer(toggleReducer, { on: initialOn, }) // The first initialOn, kept for reset. Later values are ignored. const first = useRef(initialOn) const toggle = useCallback(() => dispatch({ type: 'toggle' }), []) const setOn = useCallback( (next: boolean) => dispatch({ type: 'set', on: next }), [], ) const reset = useCallback( () => dispatch({ type: 'reset', initialOn: first.current }), [], ) return { on, toggle, setOn, reset } }
First value or latest value, run
The test sets up the case where they differ. The item mounts with initialOn false. The page then sets initialOn to true, which the hook ignores. The user opens the item and presses reset. It runs against the hook above and against a version whose reset depends on the latest initialOn.
export function useToggleLatest({ initialOn = false } = {}) { const [{ on }, dispatch] = useReducer(toggleReducer, { on: initialOn, }) const toggle = useCallback(() => dispatch({ type: 'toggle' }), []) const reset = useCallback( () => dispatch({ type: 'reset', initialOn }), [initialOn], ) return { on, toggle, reset } }
first value (ref): mounted closed page sets initialOn true: closed user opens the item: open after reset: closed latest value (dependency): mounted closed page sets initialOn true: closed user opens the item: open after reset: open empty dependency list: mounted closed page sets initialOn true: closed user opens the item: open after reset: closed
Output of a real run. The third block is the hook with an empty dependency list.
With the first value, reset closed the item. With the latest value, reset left it open, because the page had changed initialOn to true and reset obeyed it. Neither is a bug, and each is a choice. The first value says "reset means undo everything the user did". The latest value says "reset means go back to what the page currently asks for".
The first is easier to explain and matches useState. The latest needs initialOn in the dependencies of reset, so its identity changes whenever the prop does, and it asks callers to wonder why a prop that is ignored at mount is honoured at reset. This chapter uses the first and documents it.
A reset with a stale initialiser
The third block of the last output is a mistake that looks like the first value and is not the same thing. A developer writes useCallback with an empty dependency array and reads initialOn inside. The closure holds the value from the render in which the callback was made, which is the first render, so the result happens to match the first value.
It works by accident. If the hook later changes so that the callback is re-made, the behaviour changes with it. React's lint rule for hook dependencies reports the line.
lint/stale.jsx 9:5 warning React Hook useCallback has a missing dependency: 'initialOn'. Either include it or remove the dependency array react-hooks/exhaustive-deps ✖ 1 problem (0 errors, 1 warning)
Output of ESLint with eslint-plugin-react-hooks 7.1.1 on the empty-dependency version. The path is shortened. Long lines are wrapped for the page.
The warning is the useful part. Do not silence it: say what you mean. If you want the first value, keep it in a ref, as the hook does, so a reader sees that the value is deliberately fixed. If you want the latest, list the dependency. A stale closure written without a name for it is the worst of the three.
A reset that closes over the prop is a stale closure waiting to happen. Either the reducer receives the value in the action, as here, or the hook stores it in a ref that is written once.
The accordion: defaultOpenItems and reset all
The accordion has several items, so its initial value is a list. defaultOpenItems plays the part of initialOn, and the state hook that owns the list also returns reset. It keeps the first defaultOpenItems it saw.
export function useAccordionState( options: { defaultOpenItems?: string[] } = {}, ) { const first = useState(() => options.defaultOpenItems ?? [])[0] const [openItems, setOpenItems] = useState(first) const reset = useCallback(() => setOpenItems(first), [first]) return { openItems, setOpenItems, reset } }
The first line reads the option inside useState's lazy form and keeps the first result, so a caller that writes a new array literal on every render does not change what reset restores. The next test checks that, and checks reset itself.
mounted: open = results user opens fees, closes results: open = fees reset all: open = results
Output of a real run: three items, `defaultOpenItems` of `results`.
mounted: results
default prop is now ['dates']: results
open fees, then reset: resultsA second run: the default prop changes to `dates` after mount.
Reset returned the list to results. When the default prop changed to dates, the accordion kept results both at mount and after reset, because the array was read once.
In the run, the page changed initialOn to true after mount. What did reset do with the first-value hook and with the latest-value hook?
- The first-value hook closed the item. The latest-value hook left it open, because reset used the changed
initialOn.
What did ESLint report for the empty dependency list, and what is the better way to say that the first value is intended?
- It reported a missing dependency on
initialOn(react-hooks/exhaustive-deps). Keep the first value in a ref or state, so the intent is explicit.
Why does reset for the accordion restore results even after the caller's default array changes?
Part 4 · Reset with a key instead: remounting the subtree
A reset that needs no API
There is a second way to start a component over, and it needs no reset function at all. React uses key to decide whether an element is the same one as before. The React guide on preserving and resetting state says that giving a subtree a different key resets its state: the old component is removed and a new one is created from scratch, with all the state below it.
The parent holds a number, and increments it to reset. It passes the number as the key of the FAQ.
function ByKey() { const [round, setRound] = useState(0) return ( <> <button onClick={() => setRound((n) => n + 1)}> external reset </button> <KeyedFaq key={round} /> </> ) }
The reset() version of the same page calls the hook's reset, so the accordion keeps living. The two pages have one button each, and the test triggers it without moving focus, so it can see what each approach does to everything the user was doing.
function ByApi() { const acc = useAccordionState({ defaultOpenItems: [] }) return ( <> <button onClick={acc.reset}>external reset</button> <Faq acc={acc} /> </> ) }
What each one loses, run
Each page has one FAQ item with a text box inside its panel and an effect that logs setup and cleanup. The test opens the item, types Hall ticket into the box, focuses the header and then triggers the external reset button. It reads the box, the item's state, the focus and the effect log.
reset(): note text "Hall ticket", expanded=false focus on the header effect log: Note setup key change: note text "", expanded=false focus on BODY effect log: Note setup, Note cleanup, Note setup
Output of a real run, React 19.3.1, StrictMode off. `Note` is the component inside the panel.
reset() closed the item and nothing else changed. The text was still in the box, hidden with the panel, the effect never re-ran and focus stayed on the header. The key change closed the item as well, and then some: the box was empty, focus had dropped to the page body, and the effect log shows cleanup then setup, because the whole subtree had been unmounted and mounted again.
Neither result is better. A reset that is meant to throw away everything, including typed text, wants the key. A reset that should only restore the open state, and leave a half-written answer in the box, wants the hook's reset.
Choosing between them
| reset() from the hook | key change from the parent | |
|---|---|---|
| State reset | only what the hook owns | everything below the keyed element |
| Typed text in children | kept | lost |
| Effects in children | untouched | cleanup, then setup again |
| Focus inside | kept | lost, falls to the body |
| Who can trigger it | anyone holding the hook | the parent that sets the key |
| Extra API | one more function to maintain | none |
| Cost | one render | unmount and mount of the subtree |
A good rule is to expose reset for state that the hook owns and let callers use key for everything else. A caller can always add a key to your component. It cannot add a reset to it. If your hook offers reset, say in its description that it restores only the hook's own state.
One more point about keys. A key only resets what is below the keyed element. If the stale state is in the parent, a new key on the child will not touch it, and the reset will seem to do nothing.
Check your understanding
| Term | Meaning |
|---|---|
| Initial value | a value read once at mount, after which the component owns the state |
| Controlled value | a value the caller owns, which the component follows every render |
| Lazy initialiser | a function passed to useState or useReducer that React calls only to build the first state |
| Reset | a hook function that returns state to its starting value |
| Remount | unmounting a subtree and mounting a new one, which a changed key forces |
In the run, what remained after reset() and what remained after the key change?
- After
reset(): the typed text, the effect's setup and the focus on the header. After the key change: nothing. The box was empty, the effect had cleaned up and set up again, and focus was on the body.
Which approach would you use if a reset should also clear a half-written answer in a panel's text box, and why?
- A key change. It remounts everything below it, so uncontrolled inputs and child state start empty.
A parent changes the key of a child but the stale value is still there. What is a likely cause?
- The stale state lives in the parent or above the keyed element. A key resets only the state of the element it is set on and of its descendants.
All chapters · Previous: Prop Getters: Merging Caller Props With Component Behaviour