Controlled Component in React.js
React forms pose a special difficulty since you can either use React.js to fully control the element by setting and updating the input value directly, or you can let the browser handle the majority of the form elements and gather data using React change events. Since React is not establishing the value, the first method is referred to as an uncontrolled component. Because React is actively updating the input, the second method is known as a controlled component.

What is a Controlled Component?
An element of a form input whose value is totally determined by React.js state is called a controlled component. React thus takes over as the “single of truth” for the value of the input, rather than the DOM element controlling its own internal state. An update to the component’s state is required to reflect any changes made to the input’s value; user inputs do not directly affect the rendered input.
Binding a piece of state inside your React component to the value displayed in the input is the fundamental idea behind controlled components. An event handler called onChange is activated each time the user types or works with the input. After retrieving the updated input value from the event object, this handler modifies the component’s state. In order to effectively adapt the input’s value prop to the new state value, React re-renders the component whenever the state changes. State and UI alter with user activities, producing a two-way data coupling.
SPAs capture form data on the client-side and send or display it using JavaScript code. Controlled components synchronise and forecast form inputs, simplifying client-side data management.
Controlled vs. Uncontrolled Components
It helps to thoroughly comprehend uncontrolled components in order to fully understand controlled components.
Controlled Components:
- React forms are unusual because you can let the browser manage most form elements and collect data using React change events, or you can use React to fully control the element by setting and updating the input value.
- This stage uses controlled components to dynamically set and update data. Add a value prop to each component to set or change form data. Submitting resets form data.
- The input’s displayed value and the component’s state are always in sync. When feasible, form inputs should be regulated. Even if a trigger other than a user input changes the input value, this keeps the component state and value in sync.
- Give users greater control over form data by activating features like conditional input enabling/disabling, dynamic input masking, rapid validation, and form field resetting after submission.
- Because they are predictable and provide control, they are typically chosen for the majority of form elements in React applications.
Uncontrolled Components:
- Give their input value to the DOM to control. React does not set the value in the first approach, making it uncontrollable. React actively updates input, making the second approach a controlled component.
- For form programming with these, React offers very little help; frequently, you must use a ref to contact the DOM element directly and extract its value.
- For really simple forms that don’t need real-time updates or intricate validation and only need to receive the final value at submission, they are easier to implement.
- Though the input value in React’s state does not immediately reflect subsequent changes, the initial value can be set using the defaultValue prop.
- They may not be suitable for pre-populating or clearing data. React enables you to dynamically update and modify your forms to meet the requirements of your application and users, regardless of the method you use.
The complexity and requirements of your form may require you to select between controlled and uncontrolled components. Uncontrolled components are simple for pre-populating or purging data, but they may not be acceptable. Although controlled components provide the possibility of dynamic data updates, they can also introduce an abstraction level that, if not used wisely, could result in errors or needless re-renders. Controlled components are required for forms that must be cleared or pre-populated with data.
How Controlled Components Work
A few crucial steps are involved in implementing a controlled component:
Define a state variable: For your component to save the input field’s current value, a piece of state is required. It is common practice to utilise the useState Hook for functional components. State would be initialised in the constructor and managed with this.state for class components.
Bind the value prop: The value property of the input element (rather than defaultValue in JSX) needs to be set to the appropriate state variable. This indicates to React that it is in charge of regulating this input’s value.
Implement an onChange handler: Put a onChange handler on the input element. When a user types a character, this function is invoked whenever the input changes.
Update state in the onChange handler: Event.target.value returns the updated input value in onChange. Set or useState to update class or functional component states with this new value.
Prevent default form submission: Execute event often to prevent the browser from reloading the page by default.Use preventDefault() in the onSubmit handler for form submission buttons (<button type=”submit”>) or the <form> element. This lets your React application manage the client-side submission logic.
Controlled components may handle HTML form elements like <textarea>, <select>, and <input> (for text, numbers, passwords, etc.). In a choose element, the value of the selected <option>, which is the value prop, also controls the picked option.
Benefits of Using Controlled Components
Data Synchronization: The state of the component and the presented value of the input are always in sync with data synchronisation. For your form data, this offers a single, reliable of truth.
Instant Validation: Real-time validation logic can be implemented in real-time while the user types. By comparing the input value to validation rules, the onChange handler can give the user instant feedback.
Dynamic Updates: State updates change input values programmatically. This can improve “undo” capability, pre-populate forms with data, and reset fields after submission.
Conditional Rendering/Behavior: One controlled input may change the rendering or behaviour of other form elements. A submit button may not appear until all fields are completed.
Easier Debugging: Form-related issues are easier to diagnose because the component always reflects the user interface.
Code Example:
I’ll use a basic expenditure entry form to show how React’s state controls the value of an input field to demonstrate controlled components. The useState Hook will be used in this example to implement a functioning component.
import React, { useState } from 'react';
function ControlledForm() {
const [name, setName] = useState('');
const handleChange = (e) => {
setName(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
alert(`A name was submitted: ${name}`);
setName('');
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default ControlledForm;
Output:
Name:
Submit
The input field is empty. As the user types, say “John”, the input field displays “John”. The name state in React is simultaneously updated to “John”. When the user clicks the “Submit” button, an alert box appears with the message “A name was submitted: John”. After the alert is closed, the input field is automatically cleared, returning to its initial empty state.
Example of Code Explanation
UseState Hook: The useState Hook initialises a state variable called name with an empty string using the const [name, setName] = useState(”) line. To update this status, use the setName method.
Value Prop: This value is connected to the name state variable of the <input> element. This is where it’s “controlled”—the value in the name state is always what’s displayed here.
OnChange Handler: handleChange is configured for the onChange object. It is a function that is called whenever the user type. A re-render is triggered when the new value from e.target.value is updated in the name state.
HandleSubmit: e.preventDefault() allows the page to not refresh once the form is submitted. SetName(”) clears the input field by resetting the state after an alert displaying the captured name.
Conclusion
In conclusion, by tying input values to the component’s state, React.js controlled components offer a reliable and consistent method of handling form inputs. Because the state and user interface are kept in sync, developers may easily incorporate features like real-time validation, dynamic form behaviour, and fast feedback.
Controlled components make it simpler to debug and maintain form logic across complicated applications by providing a single of truth for input data. Particularly in applications that need dynamic form handling, user input, or state-driven UI updates, the greater control and flexibility they provide frequently offset the additional complexity, even though they might demand a little more boilerplate than uncontrolled components.