Hello! Welcome back to our module on "Forms and Event Handling."
In our last lesson, we focused on making our event handlers type-safe, ensuring we can confidently work with events like onClick and onSubmit in a TypeScript environment. Today, we'll put that knowledge into practice as we tackle a fundamental concept in React form management.
This lesson addresses the learning outcome: Implement controlled components to manage the state of form inputs. We will explore how to make React the "single source of truth" for our form data, giving us complete control over its behavior. This pattern is the cornerstone of building interactive, predictable, and robust forms in React.
1. What Are Controlled Components?
In a traditional HTML form, elements like <input>, <textarea>, and <select> maintain their own state internally. When a user types into an input field, the DOM updates and holds the current value. React allows us to invert this control.
A controlled component is a form element whose value is controlled by React state. Instead of the DOM managing the input's state, we manage it ourselves using the useState hook.
To understand this concept better, let's watch a brief introduction.
React JS Forms | Controlled Inputs | Learn ReactJS
This clip from Dave Gray introduces the concept of controlled components and the idea of a 'single source of truth' for form state.
Please watch the first 40 seconds of the video, from 00:00 to 00:40.
As the video mentions, we want to have one source of truth for our input's state. In React, that source is our component's state. This is sometimes referred to as managing the input's state explicitly.
This article from components.guide offers a great explanation of this idea, framing it as 'explicit state' vs. 'implicit state'.
Read the sections 'Deciding whether to control a form element' and 'Controlled form elements, or explicit state'. Focus on the bullet points that describe how state is managed explicitly with useState, value, and onChange.
The data flow for a controlled component forms a cycle:

2. Implementing a Controlled Input
Let's build a controlled <input> field step-by-step. We'll create a simple component that takes a user's name.
Step 1: Define State
First, we need a state variable to hold the value of the input. We'll initialize it with an empty string.
import { useState } from 'react';
function NameForm() {
const [name, setName] = useState<string>('');
// ...
}
Step 2: Connect the Input's value to State
Next, we render an <input> element and bind its value prop directly to our name state variable.
// Inside the NameForm component's return statement
<input
type="text"
placeholder="Enter your name"
value={name} // The input's display is now tied to the 'name' state
/>
If you were to run this code now, the input field would be un-editable. Why? Because its value is locked to the name state (which is ''), and we haven't provided any way to change that state.
Step 3: Handle Changes with onChange
To make the input interactive, we need an onChange event handler. This function will receive the change event, extract the new value from event.target.value, and use our state setter (setName) to update the state. This is where your knowledge from the previous lesson on typing events is crucial.
import { useState, ChangeEvent } from 'react';
function NameForm() {
const [name, setName] = useState<string>('');
const handleNameChange = (event: ChangeEvent<HTMLInputElement>) => {
setName(event.target.value);
};
return (
<form>
<label>
Name:
<input
type="text"
placeholder="Enter your name"
value={name}
onChange={handleNameChange} // Connect the handler
/>
</label>
<p>Current name is: {name}</p>
</form>
);
}
Now, the loop is complete. When you type in the input:
handleNameChangeis called.setNameupdates the state with the new text.NameFormre-renders.- The
<input>'svalueis now the new value from thenamestate.
The following video demonstrates this entire process within a full-fledged TypeScript project, tying together state, props, and event handling.
React & TypeScript - Course for Beginners
The freeCodeCamp tutorial on React & TypeScript provides an excellent, practical walkthrough of building a controlled input. It shows how state is defined, passed as props, and updated via event handlers.
Watch the following segments to see these concepts in action: State Creation (24:40 - 27:49): Pay attention to how useState is used to create the todo state variable with a specific type (string). Passing Props (27:49 - 30:06): Observe how the state and its setter function are passed as props to a child component, and how those props are typed using an interface. Binding value and onChange (30:06 - 30:34): This is the most critical part. See how the value of the input is set to the state, and the onChange handler updates that state.
3. Using Controlled Inputs in a Form
The real power of controlled components becomes apparent when you handle form submissions. Because the input's value is already in our component's state, accessing it is trivial—there's no need to query the DOM.
Let's add a submit handler to our NameForm.
import { useState, ChangeEvent, FormEvent } from 'react';
function NameForm() {
const [name, setName] = useState<string>('');
const handleNameChange = (event: ChangeEvent<HTMLInputElement>) => {
setName(event.target.value);
};
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
// Prevent the default browser behavior of a full-page refresh
event.preventDefault();
// The latest input value is readily available in our 'name' state
alert(`Hello, ${name}!`);
// It's also easy to reset the form after submission
setName('');
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
placeholder="Enter your name"
value={name}
onChange={handleNameChange}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}
Notice two key things in the handleSubmit function:
- We call
event.preventDefault()to stop the browser from reloading the page. - We access the form's data directly from the
namestate variable. - We clear the input field by simply calling
setName('').
The freeCodeCamp video also covers form submission, and the Dave Gray video has a particularly clear demonstration of resetting the form field.
React & TypeScript - Course for Beginners
Let's look at how to handle the form submission itself.
Watch from 32:29 to 35:20 to see how the handleAdd function is created, passed as a prop, and used in an onSubmit handler, including typing the FormEvent.
Test your understanding!
You are building a component that lets a user set a color.
- Create a controlled
<input type="color">. - The initial color in the state should be
#ffffff(white). - Below the input, display a
<div>that is 100px by 100px. - The background color of this
<div>should always reflect the current color selected in the input.
import { useState, ChangeEvent } from 'react';
function ColorPicker() {
// 1. Add state for the color
// 2. Add a change handler for the input
return (
<div>
{/* 3. Add a controlled color input here */}
{/* 4. Add a div whose style is connected to the state */}
</div>
);
}
Show answer
Here is the completed component. The pattern is identical to a text input: we use useState, value, and onChange.
import { useState, ChangeEvent } from 'react';
function ColorPicker() {
const [color, setColor] = useState<string>('#ffffff');
const handleColorChange = (event: ChangeEvent<HTMLInputElement>) => {
setColor(event.target.value);
};
return (
<div>
<input
type="color"
value={color}
onChange={handleColorChange}
/>
<div
style={{
width: '100px',
height: '100px',
backgroundColor: color,
border: '1px solid #ccc',
marginTop: '10px'
}}
/>
</div>
);
}
Conclusion
You have now mastered one of the most important patterns in React. By making form inputs controlled components, you gain fine-grained control over form data, enabling instant validation, dynamic interactions, and easy data access on submission.
Key Takeaways:
- A controlled component is a form element whose value is driven by React state.
- The component state is the single source of truth.
- This pattern is implemented by binding the input's
valueprop to a state variable and itsonChangeprop to a handler that updates the state. - This approach gives you full control over the form's data at every moment, making it easy to implement features like validation, formatting, and conditional logic.
- To reset a controlled input, you simply update its corresponding state to an initial value (e.g., an empty string).
In our next lesson, we'll build on this foundation to manage the state for a form with multiple inputs efficiently. We'll see that while creating a separate useState for every field works, there are more scalable patterns for handling complex forms.