Controlled & Uncontrolled Component
HTML elements come with their internal state which is not coupled to React.
Controlled Component
- In a controlled component, form data is handled by a React component.
UnControlled Component
- uncontrolled components, where form data is handled by the DOM itself.
- To write an uncontrolled component, instead of writing an event handler for every state update, you can use a
ref
to get form values from the DOM. - State Management: The state of the component is managed by the DOM.
- Form Elements: The form elements' values are accessed using refs.
Comparison
Aspect | Controlled Components | Uncontrolled Components |
---|---|---|
Definition | React state controls the form elements | The DOM controls the form elements |
Data Flow | One-way data binding from state to form element | Two-way data binding; form element maintains its own state |
State Management | Handled by React's state (useState or setState ) | Handled by the DOM, accessed via refs in React |
Form Element Value | Value is set via React state | Value is accessed directly from the DOM using refs |
Event Handling | Changes handled via event handlers that update the state | Less dependent on event handlers for state management |
Debugging | Easier to debug due to state being the single source of truth | Can be harder to debug as state is not managed by React |
Validation | Simplifies form validation as all data is in React state | Requires additional effort to extract values for validation |
Reusability | Better suited for reusable form components | Less suitable for complex forms |
Predictability | High, as state is the single source of truth | Lower, as state is maintained by the DOM |
Dynamic Forms | Ideal for dynamic form validation and conditional rendering | Less ideal for dynamic scenarios |
Consistency | Consistent state management across the application | Inconsistent as the state is managed by the DOM |
Integration | Better for integrating with other React components and hooks | Useful for integrating with non-React codebases |
Initial Value | Set using state | Easier to set using defaultValue or defaultChecked |
Quick Prototyping | Requires more setup | Faster to set up for simple forms |
Less Overhead | More overhead due to state management | Less overhead without state management |