
Controlled vs Uncontrolled Inputs: Pick One Source of Truth per Field
- كاتب موثّق
- React 19
محتويات المقال
value and defaultValue were interchangeable ways to fill an input, and both read their starting values on the first render, before the profile request had finished.
The common misconception
useState, pass it as value, update it in onChange. Second, value and defaultValue both just put text in the box, so you can switch between them when one of them complains.
<input value="Sara" /> and <input defaultValue="Sara" /> display exactly the same thing. The difference only shows up later, when the user types or the data changes, which is where the bugs live.
What actually happens
Every field has exactly one owner
defaultValue (or defaultChecked for checkboxes and radios) tells React what to put in the field at the start, and after that React leaves it alone. You read the value when you need it, usually on submit, by giving the input a name and reading the form data.
value (or checked), React forces the field to show that value on every render. That's why a controlled input needs an onChange that updates the state synchronously with e.target.value: if the state doesn't change, React puts the old text back after every keystroke. React's docs describe the choice in general terms: uncontrolled components need less setup, while controlled ones are the most flexible but must be fully configured by whoever owns the state.
The rules that follow from it
defaultValueis read on the first render. If the data arrives later, the field ignores it, just likeuseStateignores its initial value after the first render.A controlled valuemust never beundefinedornull. React treats a missing value as uncontrolled, and an input can't switch between controlled and uncontrolled during its lifetime. Start with""or passvalue={bio ?? ""}.valuewithoutonChangemakes a read-only field. React logs an error that suggestsdefaultValue,onChange, orreadOnlyif read-only is what you meant.Checkboxes use checkedanddefaultChecked, and a checked value must always be a boolean.
defaultValue while the profile was still null, and the bio held useState(profile?.bio), which started as undefined and became a string on the first keystroke.
import { useState } from "react";export function ProfileForm({ profile }: { profile: Profile | null }) { // undefined while loading: the textarea starts uncontrolled const [bio, setBio] = useState(profile?.bio); return ( <form> {/* Read once, on a render where profile is still null */} <input name="name" defaultValue={profile?.name} /> <textarea value={bio} onChange={(e) => setBio(e.target.value)} /> <p>{bio?.length ?? 0}/160</p> </form> );}import { useState } from "react";// Rendered only once loaded: <ProfileForm key={p.id} profile={p} />export function ProfileForm({ profile }: { profile: Profile }) { // Controlled: the counter needs the text on every keystroke const [bio, setBio] = useState(profile.bio); async function save(data: FormData) { await saveProfile({ name: String(data.get("name")), bio }); } return ( <form action={save}> {/* Uncontrolled: nothing reads it until submit */} <input name="name" defaultValue={profile.name} /> <textarea value={bio} onChange={(e) => setBio(e.target.value)} /> <p>{bio.length}/160</p> <button type="submit">Save</button> </form> );}key gives the form fresh fields whenever a different profile is opened. Each field has one owner. The name is uncontrolled, because nothing on screen depends on it until the user saves. The bio is controlled, because the counter needs its length on every keystroke, and on submit the code reads it from state rather than from the form data.
defaultValue) | value + onChange) | |
|---|---|---|
name and form data, or with a ref | ||
key | ||
When each one fits
<form action> and it receives the form's data, and after the action succeeds React resets every uncontrolled field in the form.
How to apply it in your project
Ask what each field needs while typing If nothing on screen reads a field until submit, make it uncontrolled with a nameand adefaultValue. Control it only when the UI reacts to it as the user types.Never pass undefined as a value Initialize controlled state with "", or writevalue={x ?? ""}for data from an API, and keepcheckeda boolean. This removes the uncontrolled-to-controlled error at its source.Render forms after their data Show a loading state until the record arrives, then render the form with key={record.id}, so starting values are real and switching records gives fresh fields.Treat both console errors as bugs "Changing an uncontrolled input to be controlled" and "a valueprop without anonChangehandler" each point to a field with two owners or none. Fix the field instead of silencing the message.
Key takeaways
valuesays what a field is now and makes React state its owner;defaultValueonly says how it starts.A controlled input needs a string valuefrom the first render and anonChangethat updates it synchronously.Uncontrolled fields are simpler when you only need the value on submit, and React 19 form actions hand it to you. Give every field one owner, and render forms after their data loads, with a keyto reset them.
التعليقات (0)