State and Events
💻 ReactAdd interactivity with useState and respond to clicks and typing.
State is data that changes over time. When state changes, React re-renders the component with the new value.
- Use useState.
- Update state from an event.
- Understand why updates must be immutable.
useState
Call useState with an initial value. It returns the current value and a setter.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button => setCount(count + 1)}>
Clicked {count} times
</button>
);
}Handling Input
Controlled inputs take their value from state and update it on every change.
function NameForm() {
const [name, setName] = useState("");
return (
<form => event.preventDefault()}>
<label htmlFor="name">Name</label>
<input
id="name"
value={name} => setName(event.target.value)}
/>
<p>Hello, {name || "stranger"}</p>
</form>
);
}Updating Objects and Arrays
Never mutate state directly. Create a new object or array so React can detect the change.
const [student, setStudent] = useState({ name: "Ada", score: 0 });
setStudent({ ...student, score: 85 });
const [items, setItems] = useState([]);
setItems([...items, "new item"]);Practice
- Build a counter with increment and reset buttons.
- Create a controlled text input that shows a character count.
- Add an item to an array in state without mutating it.
Hands-on exercise
Build a component with a button that:
1. Toggles a message on and off.
2. Counts how many times it has been toggled.
3. Shows the message only when it is on.
Recap
State drives the interface. Update it immutably and use the updater form when the next value depends on the old one.
Example
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
Exercises
1. Toggles a message on and off.
2. Counts how many times it has been toggled.
3. Shows the message only when it is on.
Expected Output
A working toggle with an accurate count.
Lesson Nav
React Course
0/9 lessons completed
- 1 Thinking in Components Tutorial
- 2 Props and Composition Tutorial
- 3 State and Events Tutorial
- 4 Lists, Keys and Conditional Rendering Tutorial
- 5 Forms in React Tutorial
- 6 Effects and Data Fetching Tutorial
- 7 Routing and Layouts Tutorial
- 8 Context and Shared State Tutorial
- 9 Project: A Student Dashboard Project