MIKAEELS>_

Difference between controlled and uncontrolled components in React.js

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;

Quick Recap

What is an uncontrolled component in React?

An uncontrolled component behaves like a traditional HTML form input. You read its value by accessing a ref to the DOM element (e.g. inputRef.current.value) rather than storing it in React state.

What is a controlled component in React?

A controlled component stores its value in React state via useState, updating that state on every onChange event so the input's value is always driven by React rather than the DOM.

What is the main difference between controlled and uncontrolled components?

A controlled component's value lives in React state and is set via the value prop, while an uncontrolled component's value lives in the DOM and is only read on demand through a ref.

Comments

Share your thoughts and questions below