Skip to content

Form input switching between controlled and uncontrolled

Quick summary

Your input value prop is undefined on first render but becomes a string later — React warns about switching from uncontrolled to controlled.

Why this happens

  • The state is initialized as undefined or null, making the input uncontrolled on first render

  • The value prop is conditionally set and can be undefined on some renders and a string on others

  • A form field is bound to state that starts as undefined and is set to a string after user interaction

Minimal example

✗ Broken code
function Form() {
  const [name, setName] = useState(); // undefined initially
  return <input value={name} onChange={e => setName(e.target.value)} />;
}
✓ Fixed code
function Form() {
  const [name, setName] = useState(''); // empty string initially
  return <input value={name} onChange={e => setName(e.target.value)} />;
}

Initializing state with an empty string makes the input controlled from the first render, avoiding the uncontrolled-to-controlled switch warning.

How to diagnose

  • Check the React console warning: 'A component is changing an uncontrolled input to be controlled'

  • Verify the initial state value is not undefined or null for controlled inputs

  • Inspect the value prop to ensure it is always a string (or number), never undefined

How to fix

  • Initialize the state with an empty string: useState('') instead of useState() or useState(null)

  • Provide a fallback for the value prop: value={stateValue || ''} to ensure it is always a string

  • Use defaultValue for uncontrolled inputs or always provide a defined value for controlled inputs

How to prevent

  • Always initialize controlled input state with an empty string, never undefined or null

  • Use value={x ?? ''} or value={x || ''} to guarantee the value prop is always a defined string

Related Resources

Related Glossary

Related Lessons

← Back to language