Differences between Controlled vs Uncontrolled Component in React JS

Differences between Controlled vs Uncontrolled Component in React JS

Controlled Component

A controlled component is bound to a value, and its changes will be handled in code by using event-based callbacks. This means the input form element's value is controlled by React. The form input value in a controlled component is handled by the state and can be changed using setState and useState (when using React Hooks). The state can be changed using the onChange event. The useState and setState are called when the user starts inputting a character and they then update the state of the input and set a new value for it.

import React, {Component} from 'react';

class ControlledInput extends Component {
  state = {userInput: ''};

  updateInput = (event) => {
      this.setState({
          userInput: event.target.value
      })
  } 

  render() {
    const { userInput } = this.state;
    return (
      <div> 
        <input type="text" value={userInput} onChange={this.updateInput} />
        <p>{userInput}</p>
      </div>
    );
  }
}

export default ControlledInput

Using controlled components is tiresome because you need to write an event handler for every way your data can change and pipe all of the input state through a React component. This can become particularly exhausting when you are converting a preexisting codebase to React, or integrating a React application with a non-React library. In these situations, using uncontrolled components becomes handy.

Uncontrolled Component

The uncontrolled component is like the traditional HTML form inputs that you will not be able to handle the value by yourself but the DOM takes care of handling the value of the input. Value saved can be gotten using the React ref.

import React, { useRef } from "react";

const UncontrolledInput = () => {
  const inputRef = useRef(null);

  handleSubmitButton = () => {
    alert(inputRef.current.value);
  };

  return (
    <div className="container">
      <input type="text" ref={inputRef} />
      <input type="submit" value="submit" onClick={this.handleSubmitButton} />
    </div>
  );
}

export default UncontrolledInput;

N/B: Both components can be used for form validation but the uncontrolled component can be used to handle the form validation when typing but without updating the input value with the state like the controlled. setState or useState can be used inside the handle change function to update the state.

Thank you for reading! I hope this helps someone

Happy Coding!