Forms in React – Controlled Components Explained

 In React, handling forms is different from plain HTML instead of letting the browser manage the form data, React prefers controlled components, where form inputs are controlled by React state.

What is a Controlled Component?

Controlled component make forms predictable and easy to manage.

1. State driven input values

           - The input always shows the value stored in React state.

              No mismatch between what user sees and the data.

2. Real time validation

          - You can check user input as it changes and show error messages immediaely.

3. Simplified form submissions

        - Since all data is in state, submitting a form is as simple as reading the state.

4. Better integration with React feature

       - Conditional rendering, dynamic inputs, and complex forms are easier to implement.


Example of a controlled component




Explanation of the example

The value of each input is tied to React state (name and email)
The onChange handler updates the state whenever the user types
On form submission, the state values are used directly, no need to query the DOM.

Controlled vs Uncontrolled Components

FeatureControlled ComponentUncontrolled Component
Input value      Managed by React state         Managed by DOM
Access  value       Directly from state     Using ref to access DOM
Validation    Easy to validate on change     Harder to validate in real- time
Use caseComplex forms, dynamic updates       Simple forms, legacy code

Comments