React / 23
useState, step by step
Declare a state variable, read it, and update it with its setter. Every update makes React call your component again with the new value.
The anatomy
import { useState } from "react";It's a named import from react. Then, at the top of your component:
const [count1, setCount2] = useState(03);
1 · the value
count
2 · the setter
setCount
3 · initial value
0
- The names are yours. Convention:
[thing, setThing], like[list, setList]or[isOpen, setIsOpen]. - State can hold anything: a number, a string, a boolean, an array, an object.
- A component can call
useStateas many times as it needs, once per piece of state.
What a setter call sets in motion
1 · trigger
You call the setter
setCount(1)2 · render
React calls Counter()
3 · commit
DOM gets patched
You call the setter
setCount(1)stores 1 and queues a render. It does not change thecountvariable you're holding right now.React renders again
React callsCounter()again. This timeuseState(0)returns 1 (the 0 is ignored after the first render).React commits the difference
React compares the new JSX with the previous one and updates only the parts of the DOM that changed.
Real example: a "Top rated" filter
Store the smallest thing that changes (here, whether the filter is on) and calculate the list from it:
import { useState } from "react";
import { restaurants } from "../utils/mockData";
import RestaurantCard from "./RestaurantCard";
export default function Body() {
const [topOnly, setTopOnly] = useState(false);
const visible = topOnly ? restaurants.filter((r) => r.rating >= 4.2) : restaurants;
return (
<div className="body">
<button onClick={() => setTopOnly(!topOnly)}>
{topOnly ? "Show all" : "Top rated"}
</button>
{visible.map((r) => (
<RestaurantCard key={r.id} name={r.name} rating={r.rating} />
))}
</div>
);
}Don't
Store the filtered copy
const [list, setList] = useState(restaurants);
// on click:
setList(list.filter((r) => r.rating >= 4.2));Once filtered, the other restaurants are gone from state. There's no way back without reloading the original data.
Do
Store the choice, derive the list
const [topOnly, setTopOnly] = useState(false);
const visible = topOnly ? restaurants.filter((r) => r.rating >= 4.2) : restaurants;The full list is never lost, and the button can toggle.
Each component has its own state
State belongs to one instance of a component, meaning one place it appears on screen. Render <Counter /> twice and you get two separate counts.
Two counters, two states
Try it<Counter name="A" />renders: 10
<Counter name="B" />renders: 10
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
