MIKAEELS

Explore the blog

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 onSubmit={handleSubmit}> <label>Message <input name="message" type="text" ref={inputRef} /></label> <button type="submit">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 onSubmit={handleSubmit}> <label>Message <input name="message" type="text" value={inputText} onChange={(e) => setInputText(e.target.value)} /> </label> <button type="submit">Submit</button> </form> ); }; export default Controlled;

Continue reading

Creating Custom JavaScript Functions: Best Practices and Examples · Deploy React with AWS CDK: Private S3 and CloudFront

Use defaultValue for an uncontrolled initial value, and keep a controlled input consistently controlled throughout its lifetime. React documents these rules in the input reference.

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.

Add Mikaeels Blog as a preferred source on Google

Comments

Share your thoughts and questions below