Intermediate level · Module 3: Component-Based Front Ends with React · Lesson 2 of 3
State, Events and Forms in React
Make components interactive with state and events, and build controlled forms.
In this lesson you will
- Use useState to store changing values
- Handle events and build controlled form inputs
Key concepts
useStateevent handlerscontrolled inputlifting state up
The lesson
State is data that changes over time and should update the screen, such as the search text. const [query, setQuery] = useState(""); declares it; calling setQuery re-renders the component with the new value.
Event handlers are passed as props: <button onClick={handleClick}>. In a controlled input, the value comes from state and onChange updates it, so React always knows the form's contents.
When two components need the same state, move it to their closest common parent and pass it down with props — called lifting state up. Derived values, such as the filtered list, are calculated during rendering rather than stored.
Step by step
- Add a search box with useState.
- Filter the course list from the search text during rendering.
- Build a controlled enquiry form.
- Validate the form before submitting.
Practice activity
Add search and a validated enquiry form to the catalogue.
Expected result: Typing filters the courses immediately and the form shows clear validation messages.
Check your understanding
-
What happens when you call a state setter?
Show answer
React re-renders the component with the new state.
-
What is a controlled input?
Show answer
An input whose value comes from state and is updated through onChange.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.