Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
48 views5 pages

Controlled Vs Uncontrolled Components in React

The document explains the differences between controlled and uncontrolled components in React, highlighting that controlled components rely on React state for managing input values, while uncontrolled components allow the DOM to handle their own state. Controlled components provide better predictability and validation capabilities, whereas uncontrolled components simplify setup and can be useful for quick forms or integration with non-React code. It concludes with guidance on when to use each type, recommending controlled components for dynamic forms and uncontrolled for simpler cases.

Uploaded by

vishnuvarman273
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views5 pages

Controlled Vs Uncontrolled Components in React

The document explains the differences between controlled and uncontrolled components in React, highlighting that controlled components rely on React state for managing input values, while uncontrolled components allow the DOM to handle their own state. Controlled components provide better predictability and validation capabilities, whereas uncontrolled components simplify setup and can be useful for quick forms or integration with non-React code. It concludes with guidance on when to use each type, recommending controlled components for dynamic forms and uncontrolled for simpler cases.

Uploaded by

vishnuvarman273
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Controlled vs Uncontrolled Components in React

When building forms in React, understanding controlled and uncontrolled components is key. A
controlled component is one where React is the “single source of truth” for the input’s value. Its state lives
in React (usually via useState or component state), and you update it via event handlers (e.g.
onChange ). In contrast, an uncontrolled component lets the DOM handle its own state; you access its
current value using a ref. In React’s words, controlled components handle form data via React state,
whereas uncontrolled components let the DOM manage form data 1 2 . The table below and sections
that follow summarize their definitions, usage, and differences.

Controlled Components
A controlled component renders form elements whose values are tied to React state. You set the input’s
value from state and update that state in an onChange handler. This makes the React state the “single
source of truth” for the input 3 2 . For example:

import { useState } from 'react';

function NameForm() {
const [name, setName] = useState('');
const handleChange = e => setName(e.target.value);
const handleSubmit = e => {
e.preventDefault();
alert(`Name: ${name}`);
};

return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={name}
onChange={handleChange}
placeholder="Enter your name"
/>
</label>
<button type="submit">Submit</button>
</form>
);
}

1
In this example, the <input> ’s value is always drawn from the React state variable name , and each
keystroke runs handleChange to update the state. This guarantees that React’s state controls the input
3 2 . Controlled components allow immediate validation or conditional logic on every change, since you
handle every input update in React. However, they require writing an onChange (or similar) for each input
and managing more state.

Uncontrolled Components
An uncontrolled component lets the DOM maintain its own state. You do not bind the value prop to React
state; instead, you use the defaultValue (or defaultChecked ) attribute to set an initial value, and
read the current value later via a ref. For example:

import { useRef } from 'react';

function EmailForm() {
const emailRef = useRef(null);
const handleSubmit = e => {
e.preventDefault();
alert(`Email: ${emailRef.current.value}`);
};

return (
<form onSubmit={handleSubmit}>
<label>
Email:
<input
type="email"
defaultValue="[email protected]"
ref={emailRef}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}

Here, the <input> has no value prop. Its initial value is set via defaultValue , but after mounting
React no longer controls it 4 5 . The value lives in the DOM. When the form is submitted, we access
emailRef.current.value to get the up-to-date text. This pattern is similar to plain HTML form
handling. Uncontrolled components are simpler (no state hooks or change handlers needed) and can be
useful for quick forms or when integrating non-React code. However, since React doesn’t “own” the input
value, you can’t validate or react to changes until you explicitly read the DOM value 6 7 .

2
Key Differences
• Source of Truth: Controlled inputs rely on React state, while uncontrolled inputs rely on the DOM. In
a controlled component, every change flows through React state; in uncontrolled, changes happen
in the DOM and you query them with a ref 2 8 .
• Value Binding: Controlled components use the value prop and onChange callback to handle
updates. Uncontrolled components use defaultValue (or defaultChecked ) for initial values
and access the current value via a ref 4 5 .
• State Management: Controlled means “React manages the state.” Uncontrolled means “the element
manages its own state” (like plain HTML) 2 8 .
• Predictability: Controlled forms are more predictable and in sync with your application state,
making it easy to perform validation or side-effects on every change. Uncontrolled forms have less
predictable state (since React isn’t aware of changes until you read the DOM) 9 8 .
• Integration: Uncontrolled components can simplify integration with non-React libraries or legacy
code, because they behave like normal HTML inputs. Controlled components require every update to
flow through React, which can be more boilerplate 6 9 .

Pros and Cons


• Controlled Components:
• Pros: Predictable state in React, easy validation and conditional logic on input, centralizes state for
debugging, and straightforward testing (state can be asserted) 10 .

• Cons: Requires more code (state, handlers for each input), can be verbose with many fields, and may
incur extra re-renders on every keystroke, potentially affecting performance for very large forms 11 .

• Uncontrolled Components:

• Pros: Simpler to set up (no need for change handlers or state), less code overhead, and potentially
slightly better performance because the browser handles updates without extra renders 6 12 .
• Cons: Harder to perform real-time validation or complex interactions, state is not centralized (so
debugging input value is trickier), and testing may be more involved since you must simulate DOM
interactions 13 .

Comparison Table

Aspect Controlled Component Uncontrolled Component

Source of DOM element itself (default


React state (props/state) 2
truth browser behavior) 2

Uses defaultValue /
Uses value (and/or checked ) bound to
Value prop defaultChecked for initial value
state 2
4

Change Must provide onChange (or similar) to No onChange needed; access


handling update state value via ref when needed

3
Aspect Controlled Component Uncontrolled Component

State State is managed by React (parent or State is managed by the DOM;


management component state) React doesn’t update it directly 2

Complex forms, instant validation, Simple or static forms, file inputs,


Use case
interdependent fields or when using non-React code

<input value={name} onChange={e => <input defaultValue="John"


Example
setName(e.target.value)}/> ref={nameRef}/> 5

Full control, easy validation, single source of Less boilerplate, quicker setup, may
Pros
truth 10 perform slightly faster 6 12

More code, frequent renders (on every Harder to validate, state dispersed,
Cons
keystroke) 11 more manual DOM access 13

When to Use Which


• Prefer Controlled: In most React applications, controlled components are recommended for form
inputs 1 2 . Use them when you need to respond to user input instantly (e.g. live validation),
synchronize multiple fields, or drive UI changes from input values. Controlled inputs integrate
seamlessly with React’s state and effects. For example, if you need to validate an email format or
enable/disable a button based on input, controlled components make it straightforward because
each change updates your state immediately.

• Use Uncontrolled When: Opt for uncontrolled components for simple forms or one-off inputs
where you don’t need to monitor every change. They’re also useful when integrating with third-party
libraries that expect traditional HTML inputs (since the DOM retains the data). File inputs ( <input
type="file"> ) are inherently uncontrolled (their value is read-only) 14 . If you just need to grab
the final value on submit and don't want to write change handlers, uncontrolled can be “quick and
dirty.” React’s docs note that uncontrolled components are slightly less code and easier for non-
React integration, but that “otherwise, you should usually use controlled components” 6 .

In summary, controlled components are React-managed and offer full control over form data, making
them ideal for dynamic forms. Uncontrolled components let the browser manage the data, saving
boilerplate but giving up some control. Choose controlled for complex form logic and reactive features;
choose uncontrolled for simplicity or special cases.

Sources: React documentation and expert discussions 3 1 2 9 provide guidance on form


components. These explain the concepts, usage, and trade-offs for controlled vs uncontrolled inputs in
React.

1 4 6 Uncontrolled Components – React


https://legacy.reactjs.org/docs/uncontrolled-components.html

4
2 5 reactjs - What are the Differences Between Controlled and Uncontrolled Components in
7 React? - Stack Overflow
https://stackoverflow.com/questions/42522515/what-are-the-differences-between-controlled-and-uncontrolled-
components-in-react

3 14 Forms – React
https://legacy.reactjs.org/docs/forms.html

8 Navigating React's Controlled vs. Uncontrolled Components - DEV Community


https://dev.to/ale3oula/navigating-reacts-controlled-vs-uncontrolled-components-48kb

9 10 11 Understanding Controlled and Uncontrolled components in React


12 13 https://blog.openreplay.com/understanding-controlled-and-uncontrolled-components-in-react/

You might also like