Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 132 ยท Advanced Patterns

Controlled vs Uncontrolled Components

Learn who owns the data in React components - controlled and uncontrolled inputs, value vs defaultValue, the switching warnings, a useControllableState hook and how to design components that support both.

Every piece of changing data in a React app has an owner. For a text box, the question is: who knows what is typed in it right now? There are only two possible answers. Either the browser does (the <input> element keeps its own value, and you ask for it when you need it), or React does (the value lives in your state, and the input just displays it). The first is called uncontrolled, the second controlled.

The words come from form inputs, but the idea applies to every component that holds a value: a tab bar, an accordion, a dropdown, a date picker, a slider. Understanding this one idea explains a family of warnings, stale-state bugs and API design choices. This lesson covers the inputs first, then the two famous warnings, then shows how to build your own components that support both modes, the way native inputs do.

Two ways to own a value

An uncontrolled input keeps its value inside the DOM. You may give it a starting value with defaultValue and you read the current value later, from an event or a ref. React is not involved while the user types.

A controlled input has its value supplied by React on every render, and every keystroke is reported through onChange. The state is the only truth: if you do not update it, the input does not change.

The same field, uncontrolled and controlled

In the first row React never learns what you type; "Read it" asks the DOM node at that moment and logs uncontrolled value: draft (or whatever you typed). The second row re-renders on each keystroke, so it can show a live character count. The third shows the superpower of control: because the state is the truth, you can transform or reject input before it appears. Type a1b2 and only AB shows up. An uncontrolled input cannot refuse a character without extra DOM code.

When to choose which

Need Controlled Uncontrolled
Validate or format on every keystroke Yes Awkward
Disable the submit button until the form is valid Yes Awkward
Show the value elsewhere live (preview, count) Yes Not possible without events
Several inputs that depend on each other Yes Hard
Simple form, read the values once on submit Works, but more code Simplest, fewer renders
Large forms where each keystroke re-rendering matters Needs care Cheap
File inputs (type="file") Impossible: always uncontrolled Required

Controlled Inputs and Forms covers controlled inputs in depth, and Uncontrolled Forms, File Inputs and Complex Forms covers the other side. In practice many forms mix both.

value, defaultValue and onChange

The props are strict about which mode you are in:

  • defaultValue (and defaultChecked) = uncontrolled. Used only on the first render. Changing it later does nothing.
  • value (and checked) + onChange = controlled. Read on every render.
  • Giving both value and defaultValue is a mistake; React warns, and value wins.

The "only on the first render" part of defaultValue surprises many people:

defaultValue is read once

Click "Switch user": the second user is Grace, but the first field (no key) still shows Ada, because the same input element was updated, and the DOM ignores a new defaultValue after mount. The second field has key={userId}, so React treats it as a different component, throws the old one away and builds a new input starting from Grace. Using key to restart an uncontrolled subtree is the standard way to "reset a form to new initial data" (more on keys in Reconciliation and Keys in Depth).

The two warnings everyone meets

Both warnings come from React noticing that an input is not what it claims to be. Run each of these to see the real message.

1. value without onChange

If you give an input a value, you promise to keep it up to date. Without an onChange, nothing can ever change the value, so the field is frozen.

A frozen controlled input (fails on purpose)

Try typing: nothing happens, and the console shows a warning that begins "You provided a value prop to a form field without an onChange handler". The message continues with the three fixes: add onChange, use defaultValue, or set readOnly if the field is meant to be display-only.

2. Switching from uncontrolled to controlled

An input is controlled if its value is anything other than undefined. A very common bug is initial state that starts as undefined (or a missing field of an object loaded later), so the input starts life uncontrolled and later becomes controlled.

Uncontrolled becomes controlled (fails on purpose)

Type a letter, and the console warns that a component is changing an uncontrolled input to be controlled, explaining that an input should not switch between the two for its lifetime. The same warning appears in reverse ("controlled to uncontrolled") when a value goes from a string to undefined or null.

The fixes are simple: give state a real initial value (useState('')), and when loading data, default missing fields (value={user.name ?? ''}). Use '' for "empty text", never undefined or null. For checkboxes, use false, not undefined.

Beyond inputs: components that own a value

Now the same question for your own components. Think of a <Tabs>: who knows which tab is selected? The component itself (uncontrolled) or the parent (controlled)?

  • Controlled is flexible. The parent can open a specific tab, forbid a change, synchronize two widgets, or save the selection in a URL. The cost: every user of the component must write state and a handler, even if they never care.
  • Uncontrolled is convenient. <Tabs defaultValue="a"> just works. The cost: the parent cannot read or change the selection without extra APIs.

The best reusable components support both, just like <input> does. The convention is:

Props Mode
value + onChange (onValueChange) controlled
defaultValue (+ optional onChange) uncontrolled
none uncontrolled, empty

The useControllableState hook

Implementing both modes inside every component means the same fiddly logic again and again. Extract it once into a hook (see Custom Hooks):

JSX
function useControllableState({ value, defaultValue, onChange }) {
  const isControlled = value !== undefined;
  const [internal, setInternal] = useState(defaultValue);
  const current = isControlled ? value : internal;

  function setValue(next) {
    const resolved = typeof next === 'function' ? next(current) : next;
    if (!isControlled) {
      setInternal(resolved);
    }
    onChange?.(resolved);
  }
  return [current, setValue];
}

The rules inside it are small but important:

  1. A component is controlled when value !== undefined. (Not != null: null can be a legitimate controlled value, such as "nothing selected".)
  2. In controlled mode the hook does not update its own state; it only reports the request via onChange. The parent decides.
  3. In uncontrolled mode it updates internal state and still calls onChange, so the parent can listen without owning the data.
  4. The setter accepts an updater function, like useState's.

Here are both modes in action with a Stepper component:

A Stepper that works controlled or uncontrolled

Press the first stepper's plus: it counts on its own (2) and logs uncontrolled -> 2. The next two steppers are two views of the same value; pressing one moves both, since the parent owns the number. The last one proves what control means: every press from an even number requests an odd one, so the parent refuses, the console prints refused 3, and the display never moves. In uncontrolled mode, the stepper cannot be told no.

A subtle trap: switching modes at runtime

useControllableState decides the mode on every render from value !== undefined. If a parent passes value only sometimes, the component flips modes and its internal state goes stale. Real libraries warn in development when this happens. A small guard does the job:

JSX
const wasControlled = useRef(isControlled);
if (wasControlled.current !== isControlled) {
  console.warn('A component changed from ' + (wasControlled.current ? 'controlled' : 'uncontrolled') + ' to ' + (isControlled ? 'controlled' : 'uncontrolled') + '.');
}

(Writing a ref during render is normally avoided; this is development-only diagnostics, and many libraries compute it in an effect instead.)

Form-control components: names, FormData and hidden inputs

A custom control that wants to behave like a native form field must also take part in form submission. A star rating built from buttons is not an input, so FormData knows nothing about it. The usual remedy is a hidden input that mirrors the value, which makes the component work in uncontrolled forms and with server actions (see Form Actions in React 19):

A rating control that works inside a plain form

Click the fourth star and press Send: the line under the form reads rating = 4, comment = Nice. The whole form is uncontrolled (no state in App for the fields), yet the custom control participates because of its hidden input. The same Rating could be controlled by passing value and onChange, with no change to its code.

Common bugs and how to recognise them

  • Copying props into state. const [text, setText] = useState(props.value) captures the value once. When the parent later sends a different value, the child ignores it and shows stale data. Either make the component fully controlled, or reset it by changing its key, or (rarely) sync during render. See You Might Not Need an Effect and Lifting State Up.
  • A controlled input whose handler forgets to update state. The field appears to ignore the keyboard. Check that onChange calls the setter and the setter receives event.target.value.
  • value={null}. React warns that value should not be null. Use ''.
  • Mixed modes in one parent. Passing value on the first render and undefined on the next flips the input between modes (warning above).
  • Expensive parents. A controlled input in a parent that re-renders a huge tree on every keystroke feels laggy. Move the state down into the field's own component, or use an uncontrolled field and read it on submit.
  • Using an event's value late. event.target.value must be read synchronously in the handler or copied to a variable; do not read it inside a setState updater callback that runs later.
  • Reading a ref in render to decide behavior for uncontrolled inputs: refs don't trigger renders, so the UI will not follow.

A good rule when designing your own component: make it uncontrolled by default with a defaultValue, and add value + onChange as the escape hatch for parents that need control. Most callers get the simple API; power users get the flexible one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes an <input> controlled in React?

    A controlled input gets its value prop from state and reports typing via onChange, so React is the single source of truth. A defaultValue input is uncontrolled.
  2. 2. A parent changes the defaultValue of an already-mounted input. What happens?

    defaultValue is read when the input mounts. To start over with new initial data, give the component a different key so React mounts a fresh input.
  3. 3. Which initial state causes the 'changing an uncontrolled input to be controlled' warning?

    A value of undefined means uncontrolled. When the first keystroke sets a string, the input becomes controlled and React warns. Start with an empty string instead.
  4. 4. In useControllableState, what should the setter do in controlled mode?

    The parent owns the value in controlled mode, so the component only reports the requested change. If the parent ignores it, the display stays the same.
  5. 5. Why does the Rating example render a hidden input?

    Buttons are not form fields, so FormData would not include the rating. A hidden input with the name and value makes the control work in plain and uncontrolled forms.

Summary

  • Controlled means React owns the value (value + onChange); uncontrolled means the DOM owns it (defaultValue, read through refs or FormData).
  • defaultValue is read once; use key to reset an uncontrolled component to new initial data.
  • value without onChange freezes the field; value={undefined} followed by a string switches modes. Both log warnings. Use '', never undefined or null, for empty text.
  • Control lets you validate, format, refuse and synchronize; uncontrolled is simpler and cheaper for forms read on submit; file inputs are always uncontrolled.
  • Reusable components should support both modes: value/onChange for control, defaultValue for convenience. A useControllableState hook centralizes the logic.
  • Custom form controls need a hidden input (with name) to take part in FormData and form actions.
  • Avoid copying props into state; keep one owner for each value.

Next: State Machines in React