HiveBrain v1.2.0
Get Started
← Back to all entries
patternreactCritical

What are the Differences Between Controlled and Uncontrolled Components in React?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
whatdifferencescontrolledtheuncontrolledandcomponentsreactarebetween

Problem

I'm trying to understand the distinction between Controlled and Uncontrolled components in ReactJS. Could someone please explain:

  • What is a Controlled Component?



  • How does it handle state and form data?



  • What is an Uncontrolled Component?



  • How does it differ in terms of state management?



  • Usage Scenarios:



  • When should I use one over the other?



  • Could you provide simple code examples or scenarios where each would be preferable?

Solution

This relates to stateful DOM components (form elements) and the React docs explain the difference:

  • A Controlled Component is one that takes its current value through props and notifies changes through callbacks like onChange. A parent component "controls" it by handling the callback and managing its own state and passing the new values as props to the controlled component. You could also call this a "dumb component".



  • A Uncontrolled Component is one that stores its own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.



Most native React form components support both controlled and uncontrolled usage:

// Controlled:

// Uncontrolled:

// Use `inputRef.current.value` to read the current value of 


In most (or all) cases you should use controlled components.

Code Snippets

// Controlled:
<input type="text" value={value} onChange={handleChange} />

// Uncontrolled:
<input type="text" defaultValue="foo" ref={inputRef} />
// Use `inputRef.current.value` to read the current value of <input>

Context

Stack Overflow Q#42522515, score: 378

Revisions (0)

No revisions yet.