What are controlled components and uncontrolled components in ReactJS? How do they differ from each other?
6 Answers
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
propsand notifies changes through callbacks likeonChange. 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
refto 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:
<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>
In most (or all) cases you should use controlled components.
They both render form elements
Uncontrolled component and Controlled component are terms used to describe React components that render HTML form elements. Every time you create a React component that renders an HTML form element, you are creating one of those two.
Uncontrolled components and Controlled components differ in the way they access the data from the form elements (<input>, <textarea>, <select>).