Sub topic 11
Controlled and Uncontrolled Components
Prerequisites
This chapter assumes you can write function components, use useState, pass functions as props, and handle events. You should also know why state is sometimes lifted into a parent, which the earlier chapter on lifting state covers.
The core question: who owns the state?
Every stateful component answers one question: where does the current value live? There are two answers.
- Uncontrolled: the component keeps the value in its own state. The parent can set a starting value, but it does not see or change the value afterward.
- Controlled: the parent keeps the value and passes it down as a prop. The component reports requested changes through a callback, and the parent decides what to do with them.
The built-in <input> supports both. <input defaultValue="hi" /> is uncontrolled, because the DOM holds the text. <input value={text} onChange={...} /> is controlled, because React state holds the text. Your own components can follow the same convention.
| Row | Uncontrolled | Controlled |
|---|---|---|
| Source of truth | Inside the component | In the parent |
| Initial value prop | `defaultOn` (by convention, `default` + name) | Not needed |
| Current value prop | None | `on` |
| Change notification | Optional `onChange` | Required `onChange` to make progress |
| Parent can reset or veto changes | No | Yes |
| Parent code needed | Little | More |
A component that supports both modes
Here is a Switch that picks its mode from the props it receives.
import { useState } from 'react';
export function Switch({ on: controlledOn, defaultOn = false, onChange }) {
const isControlled = controlledOn !== undefined;
const [internalOn, setInternalOn] = useState(defaultOn);
const on = isControlled ? controlledOn : internalOn;
function toggle() {
const next = !on;
if (!isControlled) {
setInternalOn(next);
}
onChange?.(next);
}
return (
<button role="switch" aria-checked={on} onClick={toggle}>
{on ? 'On' : 'Off'}
</button>
);
}Read it in three steps.
isControlledis true when the parent passed anonprop. The check uses!== undefined, soon={false}still counts as controlled.- The component always keeps
internalOn, because hooks cannot be called conditionally. It simply ignores that value when controlled. - In
toggle, the component updates its own state only when uncontrolled. In both modes it callsonChangewith the requested next value.
Using it uncontrolled
export function Settings() {
return <Switch defaultOn onChange={(next) => console.log('now', next)} />;
}The parent never stores the value. It only listens, for example to log or save it.
Using it controlled
import { useState } from 'react';
import { Switch } from './Switch';
export function Notifications() {
const [enabled, setEnabled] = useState(false);
return (
<>
<Switch on={enabled} onChange={setEnabled} />
<button onClick={() => setEnabled(false)}>Turn off</button>
</>
);
}Now the parent owns enabled. The extra button can change the switch from outside, which an uncontrolled switch cannot support.
Why offer controlled mode?
Uncontrolled mode is convenient. Controlled mode is what makes a component fit into larger designs.
- Synchronizing: two switches can share one
enabledvalue. - Validation and vetoes: the parent can ignore a requested change. For example, it can refuse to turn a setting off while a save is in progress.
- Resetting: the parent can set the value from outside, such as a "Clear all" button.
- Derived values: the parent can compute other UI from the value on every render.
A library component that supports only one mode forces its users to work around the missing one. Supporting both lets simple cases stay simple.
Edge cases and common errors
Switching modes during the component's life
If on is undefined on one render and defined on the next, the component changes from uncontrolled to controlled. This usually happens when a parent initializes state with undefined:
const [enabled, setEnabled] = useState(); // undefined at first
<Switch on={enabled} onChange={setEnabled} />On the first render, Switch is uncontrolled. After the first change, it becomes controlled. The value can jump, because internalOn and enabled are unrelated. React's own inputs warn about this exact situation. Initialize with a real value, such as useState(false).
A robust component can capture the mode on the first render and warn if it changes later.
import { useEffect, useRef } from 'react';
export function useControlledWarning(controlledValue, componentName) {
const wasControlled = useRef(controlledValue !== undefined);
const isControlled = controlledValue !== undefined;
useEffect(() => {
if (wasControlled.current !== isControlled) {
console.error(
`${componentName} changed from ${wasControlled.current ? 'controlled' : 'uncontrolled'} ` +
`to ${isControlled ? 'controlled' : 'uncontrolled'}. Pick one mode for the component's lifetime.`
);
}
}, [isControlled, componentName]);
}Call useControlledWarning(controlledOn, 'Switch') at the top of Switch.
Controlled without a handler
If a parent passes on but no onChange, the switch never changes. The parent is the source of truth, and it never updates. React treats a read-only value on an <input> the same way and warns. Decide whether your component should warn too.
Using `null` as a value
controlledOn !== undefined treats null as controlled. That is correct for values where null is meaningful, such as "no selection". Checking controlledOn != null would treat null as uncontrolled, and that breaks a controlled select that is currently empty. Choose the check deliberately and document it.
Ignoring `defaultOn` after mount
defaultOn is read only on the first render. Changing it later has no effect, as with defaultValue on an input. If you need to reset an uncontrolled component, change its key so React creates a fresh instance.
<Switch key={formVersion} defaultOn={false} />Stale state in the toggle
The example computes next from the current on. If several toggles run before a re-render, the second one sees the old value. In a controlled setting, the parent's updater form (setEnabled((v) => !v)) avoids this, but then the component must report an event rather than a computed value. Pick one contract and keep it consistent.
The same idea in a compound component
The pattern also applies to a compound component such as Tabs. The parent holds the selected value. If you add an optional value prop and an onValueChange callback, Tabs can be controlled, and defaultValue keeps it uncontrolled. The next chapter covers control props, which build on this decision.
Extracting the logic
If you support both modes in several components, the branching code repeats. A small hook can hold it:
import { useState } from 'react';
export function useControllableState({ value, defaultValue, onChange }) {
const isControlled = value !== undefined;
const [internal, setInternal] = useState(defaultValue);
const current = isControlled ? value : internal;
function setValue(next) {
if (!isControlled) {
setInternal(next);
}
onChange?.(next);
}
return [current, setValue];
}Switch then shrinks to the following code.
import { useControllableState } from './useControllableState';
export function Switch({ on, defaultOn = false, onChange }) {
const [isOn, setIsOn] = useControllableState({
value: on,
defaultValue: defaultOn,
onChange,
});
return (
<button role="switch" aria-checked={isOn} onClick={() => setIsOn(!isOn)}>
{isOn ? 'On' : 'Off'}
</button>
);
}Choosing a mode
Summary
- A controlled component receives its value and reports changes. An uncontrolled component owns its value.
- Detect controlled mode by checking whether the value prop is
undefined. - Always call hooks unconditionally, and ignore internal state when controlled.
- Name the initial-value prop
default..., and read it only on the first render. - Use
keyto reset an uncontrolled component. - Extract the branching into a hook when it repeats.
Exercise
A parent writes const [on, setOn] = useState(); and renders <Switch on={on} onChange={setOn} />. Why is this a bug with the Switch above, and how do you fix it?
Show answer
On the first render on is undefined, so Switch is uncontrolled and uses its internal state. After the first toggle, onChange sets the parent state to a boolean, so Switch becomes controlled and starts reading the parent's value, which can differ from what was shown. Fix it by giving the parent state a real initial value, such as useState(false), so the component is controlled from the first render.
Exercise
You want a "Reset" button that returns an uncontrolled Switch (with defaultOn={false}) to its default state without changing the component to controlled mode. What technique can you use?
Show answer
Change the component's key when Reset is clicked, for example by incrementing a counter in the parent and passing it as key. React discards the old instance and mounts a new one, which reads defaultOn again.
Exercise
In Switch, why does the component call useState even when it is controlled?
Show answer
Hooks must run in the same order on every render, so they cannot be called conditionally. The component always calls useState, then ignores internalOn when isControlled is true.