DEV Community

Cover image for Controlled and Uncontrolled components in react
Vishnu Satheesh
Vishnu Satheesh

Posted on

Controlled and Uncontrolled components in react

In the realm of React development, understanding the concepts of controlled and uncontrolled components is essential for building robust and maintainable applications. In this blog, we'll explore the differences between controlled and uncontrolled components in React and discuss when to use each approach effectively.

In react, there are two main approaches to handling form inputs:

  • Controlled components

  • Uncontrolled components

Controlled components

Controlled components are form inputs whose values are controlled by React state. The state variables are updated whenever the value of the input changes, and the value of the input is set explicitly through the value prop.
The onChange event handler is used to update the state.

Example:

import React, { useState } from "react";

function ControlledComponent() {
  const [name, setName] = useState("");

  const handleChange = (e) => {
    setName(e.target.value);
   }

  return ( 
   <input type="text"
    value={name}
    onChange={handleChange}
    />
   );
}
Enter fullscreen mode Exit fullscreen mode

In the example, the name state variable is used to control the value of the input field. The handleChange function updates the name state whenever the input value changes.
The value of the input is set to the current value of the name state variable through the value prop.

Uncontrolled components

Uncontrolled components are form inputs that manage their own state internally, rather than being controlled by React state.
You can access the current value of the input using a ref after the form is submitted or whenever needed.

Example:

import React, { useRef } from "react";

function UncontrolledComponent() { 
  const inputRef = useRef(null);

  const handleSubmit = (e) => {
     e.preventDefault();
     console.log(inputRef.current.value);
  };

 return (
 <form onSubmit={handleSubmit}>
  <input
   type="text"
   ref={inputRef}
   />
  <button type="submit">Submit</button>
 </form>
 );

}
Enter fullscreen mode Exit fullscreen mode

In the example, the inputRef is used to create a ref for the input field. The handleSubmit function accesses the current value of the input using inputRef.current.value.
The form submission logic can be implemented to utilize the input value as required.

Stay tuned for more insights and practical examples of React! 🚀

Buy Me A Coffee

Top comments (0)