Skip to main content

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

AspectControlled ComponentsUncontrolled Components
DefinitionReact state controls the form elementsThe DOM controls the form elements
Data FlowOne-way data binding from state to form elementTwo-way data binding; form element maintains its own state
State ManagementHandled by React's state (useState or setState)Handled by the DOM, accessed via refs in React
Form Element ValueValue is set via React stateValue is accessed directly from the DOM using refs
Event HandlingChanges handled via event handlers that update the stateLess dependent on event handlers for state management
DebuggingEasier to debug due to state being the single source of truthCan be harder to debug as state is not managed by React
ValidationSimplifies form validation as all data is in React stateRequires additional effort to extract values for validation
ReusabilityBetter suited for reusable form componentsLess suitable for complex forms
PredictabilityHigh, as state is the single source of truthLower, as state is maintained by the DOM
Dynamic FormsIdeal for dynamic form validation and conditional renderingLess ideal for dynamic scenarios
ConsistencyConsistent state management across the applicationInconsistent as the state is managed by the DOM
IntegrationBetter for integrating with other React components and hooksUseful for integrating with non-React codebases
Initial ValueSet using stateEasier to set using defaultValue or defaultChecked
Quick PrototypingRequires more setupFaster to set up for simple forms
Less OverheadMore overhead due to state managementLess overhead without state management