0% completed
Forms are essential in most web applications because, they allow users to input data, submit requests and interact with your application. In React, handling form elements like input fields, textareas, and selects is crucial when creating dynamic user interfaces.
React offers two approaches for managing these form elements: controlled and uncontrolled components. Understanding the difference between these two, when and how to use them is key to writing clean, efficient React code.
In this section, you will learn about the similarities, differences between the two approaches, when and how to use them.
A controlled component is a form element whose value is controlled by React’s state. In other words, React manages the form element's state via a state variable, and any changes to that element are handled through the useState
function in components. Meaning, a form element has a value of a state variable attached to it and is controlled throughout the application lifecycle by the state.
With controlled components, the input value is always derived from the component’s state. When the user interacts with the form element (e.g., types in an input box), an event handler updates the state, which causes a re-render of the component, and the updated state is reflected in the input element.
Controlled components in React possess some important characteristics, which includes:
Example 1
Let's look at an example of a single controlled form component:
import React, { useState } from 'react'; function ControlledForm() { const [inputValue, setInputValue] = useState(''); const handleChange = (event) => { setInputValue(event.target.value); // Update state on change }; return ( <form> <label> Name: <input type="text" value={inputValue} // The input value is controlled by state onChange={handleChange} // Update the state on every keystroke /> </label> </form> ); } export default ControlledForm;
In the example above:
value
of the input is set to the state variable inputValue
.onChange
event handler updates the state whenever the user types into the input.Example 2
Let's look at how we can control multiple input fields state:
import React, { useState } from 'react'; export default function SimpleForm (){ const [firstName, setFirstName] = useState(''); const [lastName, setLastName] = useState(''); const [email, setEmail] = useState(''); const [age, setAge] = useState(''); // Handle input changes for each state const handleFirstNameChange = (e) => setFirstName(e.target.value); const handleLastNameChange = (e) => setLastName(e.target.value); const handleEmailChange = (e) => setEmail(e.target.value); const handleAgeChange = (e) => setAge(e.target.value); // Handle form submission const handleSubmit = (e) => { e.preventDefault(); }; return ( <form onSubmit={handleSubmit}> <div> <label> First Name: <input type="text" value={firstName} //controlled state for firstName value onChange={handleFirstNameChange} /> </label> </div> <div> <label> Last Name: <input type="text" value={lastName} //controlled state for lastName value onChange={handleLastNameChange} /> </label> </div> <div> <label> Email: <input type="text" value={email} //controlled state for email value onChange={handleEmailChange} /> </label> </div> <div> <label> Age: <input type="number" value={age} //controlled state for age value onChange={handleAgeChange} /> </label> </div> <button type="submit">Submit</button> </form> ); };
Here we have multiple controlled state elements namely:
firstName
state.lastName
state.email
state.age
state.Using controlled components in forms provides several significant advantages:
Predictable Behavior: Since the component state is the single source of truth, tracking and managing changes becomes straightforward. This predictability simplifies debugging and ensures the form behaves as expected, even in complex scenarios.
Real-Time Validation: Controlled elements make it easier to implement real-time form validation. For example, you can instantly provide user feedback (like showing error messages or disabling buttons) based on the current state of the inputs.
Seamless Integration with Logic: Controlled components integrate smoothly with other React features and logic. Whether it’s for form submission, maintaining consistency across multiple inputs, or dynamically updating data, using the state provides fine-grained control and flexibility.
There are a few drawbacks to using controlled components in forms:
Performance Concerns: When dealing with forms that have many inputs or handle frequent, rapid updates (e.g., typing into a large text field), each state update triggers a re-render of the component. This can lead to noticeable performance issues, especially in large or complex applications. Optimization techniques like React.memo or debouncing may be needed to mitigate these effects.
Boilerplate Code: Controlled components require explicit management of the value and onChange properties for each input field. While this gives you full control, it also leads to more repetitive and verbose code, especially in forms with many fields. Using tools like custom hooks (e.g., useForm) or libraries (e.g., Formik or React Hook Form) can help reduce the boilerplate and simplify form handling.
In conclusion, controlled components when working with forms in React ensures that the form behaves predictably and can be easily manipulated.
.....
.....
.....