Controlled Inputs and Forms in React
Learn to control form values with React state, type change and submit events, show validation feedback, and handle form data safely with TypeScript.
Controlled fields keep the current value in React state, which lets the interface respond as a person types. This guide shows a typed email form, accessible validation feedback, and when an uncontrolled ref may be simpler. It also separates helpful client checks from server-side validation and notes what form data should stay out of logs.
Controlled Inputs and Forms in React
Introduction
A controlled React input keeps its value in state. The input displays that value, and each edit updates the state. This makes it easier to show validation errors or change the UI as the user types.
Controlled inputs work well when the UI needs to respond to field values or validation as the user types. For a tiny form you only read once on submit, an uncontrolled input with a ref may be simpler. This post uses a controlled email field.
It also covers typed change and submit handlers, inline validation feedback, and safe form handling.
Keep the input value in state
The input’s value comes from state, and its change handler updates that state. Type the event when the handler is named; JSX can infer it when the function is inline.
import { useState, type ChangeEvent, type FormEvent } from "react";
interface EmailFormProps {
onSubmitEmail: (email: string) => void;
}
function EmailForm({ onSubmitEmail }: EmailFormProps) {
const [email, setEmail] = useState("");
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
setEmail(event.currentTarget.value);
};
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
onSubmitEmail(email);
};
return (
<form onSubmit={handleSubmit}>
<label>
Email
<input
type="email"
autoComplete="email"
required
value={email}
onChange={handleChange}
/>
</label>
<button type="submit">Continue</button>
</form>
);
}
Validate and show feedback
The example uses native checks from attributes such as required, type="email", and minLength. Native validation takes little setup. Custom checks fit better when feedback needs to match your app or rules depend on several fields; add noValidate when the component will present those checks itself.
Keep feedback near the field, connect it with aria-describedby, and set aria-invalid when needed. Update the message when the value changes so it does not go stale.
For custom feedback, render the error beside the same input and keep the form’s submit handler responsible for deciding whether to continue:
return (
<>
<input
id="email"
type="email"
value={email}
onChange={handleChange}
aria-invalid={emailError ? "true" : undefined}
aria-describedby={emailError ? "email-error" : undefined}
/>
{emailError && <p id="email-error">{emailError}</p>}
</>
);
Because submission is handled on the <form>, pressing Enter in the field follows the same validation path as activating the submit button. Keep the button as type="submit"; a click-only handler misses keyboard submission.
flowchart TD
A[User edits field] --> B[Update React state]
B --> C[User submits]
C --> D{Input is valid?}
D -->|No| E[Show field feedback]
D -->|Yes| F[Send request]
F --> G[Show result]
Trade-Off Table
| Pattern | Use it when | Trade-off |
|---|---|---|
Controlled (value and onChange) |
UI or validation depends on current value | State updates on each edit |
Uncontrolled (defaultValue or ref) |
Read once at submit and no live feedback is needed | React does not own each current value |
| Native browser validation | Standard rules fit the form | Message appearance and wording vary by browser |
| Custom validation | App needs specific feedback or cross-field rules | The app must maintain and test the rules |
Production Failure Scenarios
A common bug is setting value={email} without an onChange handler. The field looks editable but React keeps restoring the same value. Keep value and change handling together. Another failure is treating client validation as proof that an email is valid: users can bypass the interface or send requests directly. Validate again on the server before saving or acting on submitted data. If two fields update independently but a cross-field rule runs only on blur, submit can still accept an invalid combination; validate the complete payload at submit time.
Security and Compliance Notes
Treat form values as untrusted input. On the server, validate shape, length, and allowed values, then encode or parameterize values before using them in queries or HTML. Client checks improve the experience; server checks enforce the rule. For personal or payment data, collect only what the feature needs and avoid storing it in browser logs.
Observability Checklist
- Count validation failures by field and category.
- Attach a request ID to failed submissions.
- Keep email addresses, passwords, and full payloads out of logs.
Common Pitfalls / Anti-Patterns
Do not combine value with no change handler, clear errors before the user can understand them, or rely on browser validation as the only rule. Keep each error associated with its field and preserve labels for accessible input.
When to Use / When NOT to Use
Use controlled fields when the UI needs live validation, conditional controls, or immediate feedback. An uncontrolled field can be simpler when its value is read only at submit. Avoid duplicating a field in both React state and a separate DOM source of truth.
Quick Recap Checklist
- Store values in state when the UI needs to react to edits.
- Pair every controlled
valuewith anonChangehandler. - Type events for the element that produced them.
- Connect validation text to its field and announce errors accessibly.
- Validate submitted data on the server too.
Interview Questions
Its displayed value comes from React state, and an event handler updates that state when the user edits the field.
Use ChangeEvent<HTMLInputElement> for an input change and FormEvent<HTMLFormElement> for form submission.
Client side code can be bypassed. The server must check submitted values before saving them or using them in other operations.
Pair its state-backed value with an onChange handler that updates that state.
- Without the handler, React restores the same value after each edit.
- Use
defaultValuefor an uncontrolled starting value.
It can fit a small form whose current value is read only at submit.
- A ref can access the element when needed.
- Use controlled state for live validation or UI that depends on edits.
It disables the browser's automatic validation prompt for that form.
- The app can display its own field feedback.
- It does not remove the need to validate submitted data.
Give the message an ID and reference it with aria-describedby.
- Set
aria-invalidwhen the current value has an error. - Use a visible label that points to the input's ID.
The form receives submissions from its submit button and keyboard interaction.
- Call
preventDefault()when React will process the values. - Do not attach the only handler to a mouse click on one button.
It gives quick feedback but does not enforce data rules.
- Requests can be sent without using the browser form.
- Validate shape and allowed values on the server before acting.
Logs should not contain passwords, full form payloads, or unnecessary personal data.
- Count validation failures by field and category.
- Use a safe request ID to correlate failed submissions.
Further Reading
- For typed event signatures, read React event handling and event types.
- React state with useState explains the render snapshots behind controlled values.
- Review accessible React interfaces for labels, focus, and error feedback.
- For server responses after submission, see fetching and typing API data.
- Test user-visible form behavior with React component and interaction testing.
- React’s references cover input and form, with a guide to responding to events.
Conclusion
Controlled inputs make React state the source of truth for fields that affect the UI. Type each event, show feedback beside the field, and choose native or custom validation based on the form’s needs. Keep the server as the final validation boundary.
Category
Related Posts
React Event Handling and Event Types
Learn to type React click, change, and form handlers in TypeScript, pass callbacks through props, and validate user input safely with clear examples.
React Props, Children, and Component Composition
Learn to pass data and callbacks through React props, use children for flexible layouts, and compose small components without building giant prop APIs.
React Custom Hooks for Reusable Stateful Logic
Learn how React custom hooks reuse stateful logic, follow use* naming and call rules, type inputs and results, and keep each call's state independent.