Sub topic 7
Uncontrolled inputs and refs
This chapter assumes you know useState, event handlers, and the controlled input pattern from the earlier chapters. You should also be comfortable with destructuring and arrow functions.
What "uncontrolled" means
A controlled input gets its text from React state. React is the source of truth, and every keystroke goes through onChange and setState.
An uncontrolled input does the opposite. The browser's DOM element keeps the current text. React renders the input once and then leaves it alone. When you need the value, you ask the DOM for it.
The difference comes from one prop. If you pass value (or checked for checkboxes), React controls the input. If you leave it out, the input is uncontrolled.
// Controlled: React owns the text.
<input value={name} onChange={(e) => setName(e.target.value)} />
// Uncontrolled: the DOM owns the text.
<input name="name" />Plain HTML forms work the way uncontrolled inputs do. React just gives you ways to reach into them.
Reading a value with a ref
A ref is an object that holds a value React does not track for rendering. You create one with useRef. It has a single property, current. When you pass a ref to an element's ref prop, React sets ref.current to the DOM node after the element is mounted.
import { useRef } from 'react';
export default function NewsletterForm() {
const emailRef = useRef(null);
function handleSubmit(e) {
e.preventDefault();
const email = emailRef.current.value;
console.log('Subscribing', email);
}
return (
<form onSubmit={handleSubmit}>
<label>
Email
<input ref={emailRef} type="email" defaultValue="" />
</label>
<button type="submit">Subscribe</button>
</form>
);
}Things to notice:
useRef(null)starts withcurrentset tonull. React fills it in after the first render.- The component does not re-render while the user types. Nothing in state changed.
emailRef.current.valueis the browser'sHTMLInputElement.value, which is always a string.
Rules for refs
- Read and write
ref.currentin event handlers and effects. Do not read it during rendering. On the first render it is stillnull, and later renders cannot rely on it being up to date. - Changing
ref.currentdoes not trigger a render. If the screen must change when a value changes, that value belongs in state. - Each field needs its own ref. For a form with many fields, one ref per input gets tedious. That is the main reason to prefer
FormData, covered in the next chapter.
Setting starting values: defaultValue and defaultChecked
An uncontrolled input still needs a starting value sometimes, such as an edit form that shows saved data. Use defaultValue. For checkboxes and radios, use defaultChecked. These props are read only when the element is first created.
export default function PreferencesForm({ saved }) {
return (
<form>
<input name="nickname" defaultValue={saved.nickname} />
<select name="theme" defaultValue={saved.theme}>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<label>
<input
name="digest"
type="checkbox"
defaultChecked={saved.digest}
/>
Weekly digest
</label>
<textarea name="bio" defaultValue={saved.bio} />
</form>
);
}Two details matter here:
- In React, a
<select>takesdefaultValueon the<select>itself. Do not putselectedon an<option>. - A
<textarea>takes its starting text throughdefaultValue, not as child text.
Changing defaultValue later does nothing
If the saved prop changes after the form has mounted, the inputs do not update. defaultValue describes the initial value only. The user's typing lives in the DOM and is never overwritten.
When you want a new record to produce a fresh form, give the form a key that changes with the record. React then throws away the old DOM and builds a new one with the new defaults.
<PreferencesForm key={saved.id} saved={saved} />This is the same technique used for controlled forms. The earlier chapter on initial values and resetting covers it in more detail.
A good use of refs: moving focus
Refs are not only for reading values. They give you access to the DOM node, so you can call browser methods such as focus(). Focus management is a standard use, because it is imperative by nature. You cannot describe it well with state.
This form checks the field on submit and puts the cursor in it when it is empty:
import { useRef, useState } from 'react';
export default function CouponForm() {
const codeRef = useRef(null);
const [message, setMessage] = useState('');
function handleSubmit(e) {
e.preventDefault();
const code = codeRef.current.value.trim();
if (code === '') {
setMessage('Enter a coupon code.');
codeRef.current.focus();
return;
}
setMessage('Applied ' + code);
}
return (
<form onSubmit={handleSubmit}>
<label>
Coupon code
<input ref={codeRef} name="code" defaultValue="" />
</label>
<button type="submit">Apply</button>
<p role="status">{message}</p>
</form>
);
}The input is uncontrolled, but the component still has state, for the message. Mixing the two is fine. The input's text stays in the DOM, and only the message is React state.
The role="status" paragraph is a live region, so screen readers announce the message when it changes.
Controlled or uncontrolled?
| Need | Controlled | Uncontrolled |
|---|---|---|
| Show the value elsewhere as the user types | Yes | No, the value is not in React |
| Validate on every keystroke | Yes | Awkward |
| Disable the submit button until the form is valid | Yes | Awkward |
| Format input as it is typed (phone numbers) | Yes | Not practical |
| Read values once, on submit | Works, with more code | Simple |
| Many fields, simple submit | More code | Less code, especially with `FormData` |
| Integrate with non-React code or a DOM library | Harder | Easier |
| File input | Not possible | Required |
| Re-render cost on every keystroke | Paid | None |
A reasonable default is to start with controlled inputs when the UI reacts to what the user types. Choose uncontrolled when you only need the values at submit time.
Common errors
Passing value without onChange
// The user cannot type. React warns in the console.
<input value="fixed" />React treats this input as controlled, so it keeps resetting the text to "fixed". If you want a starting value that the user can edit, use defaultValue. If you want a read-only display, add readOnly.
Switching between controlled and uncontrolled
const [name, setName] = useState(); // starts as undefined
<input value={name} onChange={(e) => setName(e.target.value)} />While name is undefined, the input is uncontrolled. After the first keystroke it becomes controlled, and React warns about the switch. Initialize state with ''. The same applies to checked, which should start as false rather than undefined.
Reading a ref too early
const inputRef = useRef(null);
console.log(inputRef.current.value); // TypeError on first renderDuring the first render, inputRef.current is null. Move the read into an event handler or an effect.
Expecting defaultValue to follow props
As shown earlier, a changed defaultValue is ignored after mount. Use key to reset, or switch to a controlled input if the value must track props continuously.
Setting the value through the ref
Writing ref.current.value = 'x' works, and some code uses it to reset a field. It bypasses React, so use it sparingly. For whole-form resets, form.reset() or a changed key is cleaner.
File inputs are always uncontrolled
<input type="file"> is the one case where you have no choice. Browsers do not let scripts set the selected file, so React cannot control the field. You read files from the DOM element when you need it:
import { useRef } from 'react';
export default function AvatarUpload() {
const fileRef = useRef(null);
function handleSubmit(e) {
e.preventDefault();
const file = fileRef.current.files[0];
if (file) {
console.log(file.name, file.size);
}
}
return (
<form onSubmit={handleSubmit}>
<input ref={fileRef} type="file" accept="image/*" />
<button type="submit">Upload</button>
</form>
);
}files is a FileList, so files[0] is undefined when nothing was selected. Always check before using it.
Exercise
A developer writes <input value={user.nickname} /> to show a saved nickname in an edit form, and users report they cannot type in the field. What is the cause, and what are two ways to fix it?
Show answer
Passing value without onChange makes the input controlled, so React resets the text to user.nickname on every render and the typing has no effect. Fix 1: keep the input controlled by storing the nickname in useState (initialized from user.nickname) and adding an onChange that updates it. Fix 2: make it uncontrolled by using defaultValue={user.nickname} and reading the value on submit through a ref or FormData.
Exercise
Why is it a bug to write const text = inputRef.current.value; directly in the body of a component, and where should that line go instead?
Show answer
During the first render the element has not been mounted, so inputRef.current is still null and reading .value throws a TypeError. Refs are also not tied to rendering, so a render-time read can be stale. Put the line inside an event handler such as onSubmit, or inside an effect, which both run after the element exists.