Skip to content
ClapelloNotes by Barath
ReactCh 05 · 2/6
Beginner3 min readUpdated

React / 23

useState, step by step

TL;DR

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

what state holds for this render

2 · the setter

setCount

stores a new value and asks React to render again

3 · initial value

0

used on the first render only, then ignored
useState returns a pair. You name both halves with array destructuring; [thing, setThing] is the convention.
  • 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 useState as 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)
queues a render

2 · render

React calls Counter()

this time useState gives back 1, so the JSX says 1
new JSX vs old

3 · commit

DOM gets patched

only the text 0 → 1 changes
A setter doesn't change the screen directly. It asks for a new render; React calls your component again and patches only what changed.
  1. You call the setter

    setCount(1) stores 1 and queues a render. It does not change the count variable you're holding right now.
  2. React renders again

    React calls Counter() again. This time useState(0) returns 1 (the 0 is ignored after the first render).
  3. 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:

Body.jsx
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: 1

0

<Counter name="B" />renders: 1

0

Same component, used twice. Each copy keeps its own count, and clicking one re-renders only that one: watch the other badge stay still.

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.