ReactJS: What are Controlled & Uncontrolled Component.

Mar 14, 2023ยท

6 min read

ReactJS: What are Controlled & Uncontrolled Component.
Play this article

Introduction

If you have been using ReactJS for making any form then you must have encountered an error regarding the uncontrolled component and went back to handle it. In this article, we will see all about the Controlled & Uncontrolled component in React.

Controlled Component

In React, a controlled component is a component that receives its value from a parent component via props and notifies changes back to the parent component via a callback function. This means that the parent component has full control over the value of the controlled component.

Controlled components are often used in forms, where the parent component manages the form state and passes the current value of the form inputs as props to the child components. When the user interacts with the form, the child components notify the parent component of any changes by calling the callback function provided as a prop.

Using controlled components in React allows for a more predictable and controlled flow of data within the application, as the data flow is always from parent to child and not the other way around. This also allows for easier testing and debugging of the application, as the state of the components can be easily tracked and traced.

Overall, controlled components are an important concept in React development and are often used in building complex applications with forms or other types of user input.

Example of Controlled Component

import React, { useState } from 'react';

function ControlledInput() {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    event.preventDefault();
    setValue(event.target.value);
  };

  return (
    <div>
      <label htmlFor="name">Name:</label>
      <input id="name" type="text" value={value} onChange={handleChange} />
      <p>{value}</p>
    </div>
  );
}

export default ControlledInput;

In this example, the ControlledInput component is a controlled component because its value is managed by the parent component using useState and is passed down to the child component as a prop. The input field's value is set to value, which is controlled by the parent component.

When the user types in the input field, the onChange event is fired, which calls the handleChange function. This function updates the value state using setValue, which triggers a re-render of the component with the new value. The updated value is displayed in the p element below the input field.

Because the value of the input field is controlled by the parent component, it's easy to validate and manipulate the input value before submitting it to a backend or another part of the application. Additionally, because the value is stored in the parent component's state, it's easy to pass it down to other components or share it with other parts of the application.

Uncontrolled Component

In React, an uncontrolled component is a component that manages its state internally, without relying on any external data source or managing its state using a parent component. Uncontrolled components typically use the DOM to manage their state, and the component's state is updated directly by user interaction with the component.

An example of an uncontrolled component is a simple HTML input element. When a user types into the input field, the DOM updates the input's value attribute to match the user's input. The component itself is responsible for managing this state and doesn't rely on any external data source to manage its state.

While uncontrolled components can be useful for simple user inputs, they can be less predictable and harder to debug compared to controlled components. Uncontrolled components are often used in scenarios where the value of the component doesn't need to be shared with other components in the application or when the value is only needed temporarily, such as in a search bar or a password input field.

In summary, uncontrolled components manage their state internally, relying on the DOM to manage the state, and can be useful in simple scenarios where the value doesn't need to be managed or shared with other components.

Example of Uncontrolled Component

import React from 'react';

function UncontrolledInput() {
  const handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.target);
    console.log(data.get('name'));
  };

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Name:</label>
      <input id="name" type="text" name="name" />
      <button type="submit">Submit</button>
    </form>
  );
}

export default UncontrolledInput;

In this example, the UncontrolledInput component is an uncontrolled component because its value is managed internally by the component using the DOM. The input field doesn't have a value prop or an onChange event, so its state is updated directly by user interaction with the component.

When the form is submitted, the handleSubmit function is called, which prevents the default form submission behaviour and logs the input value to the console. The input value is retrieved using the FormData API, which reads the value directly from the DOM.

Because the input value is managed internally by the component, it's harder to validate and manipulate the input value before submitting it to a backend or another part of the application. Additionally, because the value is stored in the DOM, it's harder to pass it down to other components or share it with other parts of the application. However, uncontrolled components can be useful for simple forms or inputs where the value doesn't need to be managed or shared with other components.

Difference between Controlled and Uncontrolled component

The main difference between controlled and uncontrolled components in React is how they handle data flow and manage their state:

  • Data flow: In a controlled component, the value of the component is passed down from the parent component via props, and any changes to the value are communicated back to the parent component via callbacks. This means that the parent component has full control over the component's value and can manage it directly. In contrast, an uncontrolled component manages its value internally, and the parent component can only access the value by using a ref.

  • State management: In a controlled component, the state of the component is managed by the parent component, which passes down the current value as a prop. This allows the parent component to have complete control over the component's state and enables more predictable behaviour. In contrast, an uncontrolled component manages its state internally, using a combination of internal state and DOM manipulation. This can be less predictable and harder to debug.

  • Usage: Controlled components are typically used when you need to have more control over the state of a component, such as in forms or when building reusable components. Uncontrolled components are often used when you need to handle user input but don't need to manage the state of the component, such as with simple input fields or buttons.

Conclusion

Overall, the choice between using a controlled or uncontrolled component depends on the specific needs of the application and the development team's preferences. Controlled components can provide more predictability and control, but require more code to manage. Uncontrolled components can be easier to use in simple scenarios but can be harder to manage in more complex situations. I hope this article helped you. Thanks for reading ๐Ÿ˜€.

Did you find this article valuable?

Support Kushal Karan by becoming a sponsor. Any amount is appreciated!

ย