Photo by Fili Santillán on Unsplash
Difference between controlled and uncontrolled components in React.js
Uncontrolled Component
An uncontrolled component is similar to a traditional HTML form input element. You can get the value of the input by accessing the reference to the input.
import { useRef } from "react";
const Uncontrolled = () => {
const inputRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
console.log(inputRef.current.value);
};
return (
<form>
<input type="text" ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</form>
);
};
export default Uncontrolled;
Controlled Component
On the other hand, we have a controlled component. Rather than accessing the value of the input through the reference of the element, we can store the value in React state.
import { useState } from "react";
const Controlled = () => {
const [inputText, setInputText] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
console.log(inputText);
};
return (
<form>
<input
type="text"
value={inputText}
onChange={(e) => setInputText(e.target.value)}
/>
<button onClick={handleSubmit}>Submit</button>
</form>
);
};
export default Controlled;