React · Lesson 5 of 15 · 4 min
Event Handling & Form Management
This is where you show you can build interactive UIs and articulate the most common React pattern: the controlled component.
Why React Has Its Own Event System
React doesn't use native browser events directly. It wraps them in a SyntheticEvent object. In an interview, you need to know why.
First, for cross-browser consistency. Browser event implementations have quirks. React's wrapper normalizes them, so properties like e.target.value work predictably everywhere.
Second, for performance. React uses event delegation. It attaches a single event listener at the app root, not one for every element. When an event fires, the root listener catches it and dispatches it to the correct component in the tree. This reduces memory usage, especially in large lists.
The only methods you need to know cold are e.preventDefault() to stop default browser behavior (like a form submission reloading the page) and e.stopPropagation() to stop an event from bubbling up to parent elements. Use the latter sparingly.
Controlled vs. Uncontrolled: The Fundamental Form Pattern
This is the most important concept in this lesson. You will be asked to explain the difference.
A controlled component is the standard, idiomatic way. The form input's value is "controlled" by React state. The data flows in a loop: state sets the input value, the user's typing triggers onChange, the handler updates the state, and the component re-renders with the new value.
This makes React state the single source of truth. It's predictable and allows for instant validation, conditional logic, or formatting.
An uncontrolled component is an escape hatch. The DOM manages the input's state. You use a ref to "pull" the value from the DOM when you need it, typically on form submission.
How to answer "controlled vs. uncontrolled": "A controlled component's value is driven by React state, making the state the single source of truth. It's the default for forms in React because it enables easy validation and conditional logic. An uncontrolled component lets the DOM manage its own state; you use a ref to get the value when needed. It's simpler for basic forms or when integrating with non-React libraries, but you lose the benefits of a single source of truth."
Implementing a Controlled Form
A typical form needs to manage state for multiple inputs, handle submission, and perform validation.
The trap: Don't use a separate useState for every input. Group related fields into a single state object. It's cleaner and scales better.
Use a single handleChange function. By giving each input a name attribute that matches a key in your state object, you can update the correct piece of state dynamically. This is a robust pattern.
Validate on submit. Running validation onChange can create a noisy, frustrating user experience. It's usually better to check all fields when the user is done.
The trap: Always call e.preventDefault() in your onSubmit handler. Forgetting this is a classic junior mistake; the browser will perform a full page reload and your application state will be lost.
import React, { useState } from 'react';
function RegistrationForm() {
const [formData, setFormData] = useState({ username: '', email: '' });
const [errors, setErrors] = useState<{ [key: string]: string }>({});
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData(prev => ({ ...prev, [name]: value }));
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const newErrors: { [key: string]: string } = {};
if (!formData.username) newErrors.username = 'Username is required';
if (!/\S+@\S+\.\S+/.test(formData.email)) {
newErrors.email = 'Email is invalid';
}
setErrors(newErrors);
if (Object.keys(newErrors).length === 0) {
console.log('Form submitted:', formData);
// API call would go here
}
};
return (
<form onSubmit={handleSubmit}>
<input
name="username"
value={formData.username}
onChange={handleChange}
placeholder="Username"
/>
{errors.username && <p>{errors.username}</p>}
<input
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email"
/>
{errors.email && <p>{errors.email}</p>}
<button type="submit">Register</button>
</form>
);
}
This example shows a scalable pattern: one state object, one change handler, and validation on submit.
Justifying Uncontrolled Components
You should only reach for this pattern in a few specific situations. Knowing them shows you understand the trade-offs.
The canonical example is the file input: <input type="file">. Its value is a read-only FileList object controlled by the user's operating system, not your app. You must use a ref to access the selected files.
Another case is integrating a non-React UI library, like a jQuery date picker, that directly manipulates the DOM. A ref is your bridge to the DOM element it controls.
Finally, you might use it to avoid re-renders on every keystroke in a performance-critical scenario. But this is a micro-optimization. Do not cite this as your primary reason unless you have measured a real performance problem.
When using an uncontrolled component, set its initial value with the defaultValue prop. If you use value, React will make the input read-only unless you also provide an onChange handler, which effectively turns it back into a controlled component.
Try it
Build a login form with two controlled inputs (email, password) and a submit button. On submit, validate that neither field is empty. If valid, log the form data to the console. If invalid, display an error message under the relevant field. This should take about 15 minutes.
Next: We'll manage navigation and URLs in a single-page app with React Router for SPA Navigation.
Lock it in — apply this lesson under interview conditions.