DEV Community

Javanshir Abdullayev
Javanshir Abdullayev

Posted on

Understanding React: The Difference Between Controlled and Uncontrolled Components

Introduction

Hey there! When building React applications, there are two ways to manage the state of your components: controlled and uncontrolled components. Each approach has its own advantages and disadvantages. By understanding their differences, you can choose the right one for your project. Keep up the great work! 😊

Controlled Components

A controlled component is a React component that gets its value from props and notifies changes through callbacks like onChange. In other words, its value is controlled by a parent component. This can be really useful when you need to manage the state of your component from a parent component, such as a form.

Let's take an example. Say you have a form with an input field. You can create a controlled component by passing a value and an onChange callback as props. The value will be the value of the input field, and the onChange callback will be called every time the user types something in the input field. The parent component can then update the value of the input field by updating the props passed to the controlled component.

The main advantage of controlled components is that the parent component has full control over the state of the component. This makes it easier to implement complex features like validation or logic that depends on the state of multiple components. However, controlled components require more code to set up and maintain.

Here's an example of a controlled component in React:

import React, { useState } from 'react';

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

  function handleChange(event) {
    setValue(event.target.value);
  }

  function handleSubmit(event) {
    event.preventDefault();
    console.log('Submitted value:', value);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Controlled Input:
        <input type="text" value={value} onChange={handleChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have a controlled component called ControlledComponent that includes a form with a single text input. The value of this input is stored in the component's state using the useState hook.

We also have two functions: handleChange and handleSubmit. The handleChange function updates the component's state with the current value of the input, and the handleSubmit function logs the submitted value to the console.

Finally, the input element is a controlled component because its value is bound to the value state variable using the value prop. When the user types something into the input, the handleChange function is called, which updates the value state variable and causes the input to re-render with the new value.

By using a controlled component, we have complete control over the state of the input and can perform validation or manipulation of the data before submitting it to the server.

Uncontrolled Components

An uncontrolled component refers to a React component that manages its own state internally via refs or other techniques. This means that its value is not under the control of a parent component. Typically, an uncontrolled component comes in handy when you need to manage the state of your component internally, such as a simple input field.

For example, if you have a simple input field that doesn't require any validation or logic, you can create an uncontrolled component using refs to get the value of the input field. The component can then manage its own state internally without requiring any props or callbacks from a parent component.

The main benefit of using uncontrolled components is that they require less code to set up and maintain. This makes them an ideal choice for simple components that don't require complex state management. However, it's worth noting that uncontrolled components can be harder to debug and test, especially if they rely on internal state.

Here's an example of an uncontrolled component in React:

import React from 'react';

function UncontrolledComponent() {
  function handleSubmit(event) {
    event.preventDefault();
    console.log('Submitted value:', event.target.text.value);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Uncontrolled Input:
        <input type="text" name="text" />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have an uncontrolled component called UncontrolledComponent that includes a form with a single text input. Unlike the controlled component example, the value of this input is not stored in the component's state.

Instead, when the form is submitted, we access the value of the input directly from the event object using event.target.text.value. This means that the value of the input is not controlled by React and can potentially be modified by the user outside of React's control.

Uncontrolled components are useful when you don't need to perform any validation or manipulation of the data before submitting it to the server. They can also be more performant than controlled components because React doesn't have to re-render the component every time the user types something into the input.

However, they do have some limitations, such as limited control over the input value and potential for inconsistent behavior across different browsers or devices.

Choosing Between Controlled and Uncontrolled Components

Choosing between controlled and uncontrolled components depends on the specific requirements of your project. Here are some factors to consider:

  • Complexity: If you need to implement complex features like validation or logic that depends on the state of multiple components, controlled components are a better choice because they give the parent component full control over the state of the component.
  • Simplicity: If you are building a simple component that doesn't require complex state management, uncontrolled components can be a good choice because they require less code to set up and maintain.
  • Performance: Controlled components can be slower than uncontrolled components because they require more rendering cycles. However, in most cases, the performance difference is negligible.
  • Debugging and Testing: Debugging and testing controlled components is easier than uncontrolled components because the state is managed by the parent component. However, if you are building a simple component that doesn't require complex state management, debugging and testing an uncontrolled component is relatively straightforward.

Conclusion

In summary, controlled and uncontrolled components are two different approaches to managing the state of React components. Controlled components are useful when you need to manage the state of a component from a parent component, while uncontrolled components are useful when you need to manage the state of a component internally. Both approaches have their own benefits and drawbacks, and choosing the right one depends on the specific requirements of your project. By understanding the differences between these two approaches, you can make an informed decision about which one to use in your React applications. Hope this helps! Let me know if you have any other questions. :)

Additional Resources

Top comments (0)