React Basics: Build Interactive Interfaces
State and Events
In this lesson you will
- Store changing data with useState
- Respond to events such as clicks and typing
- Explain why you must use the setter function
Introduction
Apps change as people use them: a counter goes up, a menu opens, text is typed. Data that changes over time and affects what is shown is called state.
The simple explanation
State is a component's memory. When state changes, React shows the component again with the new value.
useState
The useState hook gives you a value and a function to change it:
React (JSX)
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}useState(0)starts the count at 0.- It returns a pair: the current value (
count) and a setter (setCount). onClickis an event handler. When the button is clicked,setCountruns and React redraws the component.
Quick quiz
Why do we call setCount(count + 1) instead of count = count + 1?
Typing into an input
Inputs are usually controlled: their value comes from state, and typing updates the state.
React (JSX)
function NameBox() {
const [name, setName] = useState("");
return (
<div>
<input value={name} onChange={(e) => setName(e.target.value)} />
<p>Hello, {name || "stranger"}!</p>
</div>
);
}e.target.value is what is currently in the box. As you type, the greeting updates.
Rules of hooks
- Call hooks at the top level of a component, not inside loops or conditions.
- Only call hooks inside components (or your own custom hooks).
- Never change state directly. Always use the setter, and treat state values as read-only.
State per component
Each copy of a component has its own state. Two Counter components on the page count independently.
Try it yourself
Build a LikeButton that shows "Like" and a count. Each click adds one. As a bonus, change the label to "Liked" after the first click.
Summary
- State is data that changes and affects what is on screen.
useStategives a value and a setter, and calling the setter re-renders.- Handle events with props such as
onClickandonChange.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading