React Fundamentals

0% completed

Previous
Next
Controlled Components in Forms

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.

What Are Controlled Components?

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.

Key Characteristics of Controlled Components

Controlled components in React possess some important characteristics, which includes:

  • State management: The value of the input field is bound to the component’s state.
  • Event handling: Changes to the input field trigger an event handler that updates the state.
  • Re-rendering: When the state is updated, the component re-renders, keeping the input value in sync with the state.

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:

  • The value of the input is set to the state variable inputValue.
  • The onChange event handler updates the state whenever the user types into the input.
  • The component re-renders each time the state changes, ensuring the input’s value is always in sync with the state.

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:

  • The text input field for firstName state.
  • The text input field for lastName state.
  • The text input field for email state.
  • The text input field for age state.

Advantages of Controlled Components

Using controlled components in forms provides several significant advantages:

  1. 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.

  2. 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.

  3. 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.

Disadvantages of Controlled Components

There are a few drawbacks to using controlled components in forms:

  1. 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.

  2. 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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next