Skip to content

Instantly share code, notes, and snippets.

@mikaeelkhalid
Created October 21, 2021 06:58
Show Gist options
  • Save mikaeelkhalid/f04d8f402d286910bc6d61f07aeff332 to your computer and use it in GitHub Desktop.
Save mikaeelkhalid/f04d8f402d286910bc6d61f07aeff332 to your computer and use it in GitHub Desktop.
Difference between controlled and uncontrolled components in react

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.

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 React, { 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;
import React, { 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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment