DocsLearn

State

State is a value a component remembers between draws. Change it, and React draws the component again with the new value: the text, the classes, whatever read it.

In this lesson

  • how to make a value that changes, and read and change it;
  • how to change it from what it was;
  • how to work out other values from it, without keeping them twice;
  • how to keep several values that change together.

Make a value that changes

import { useState } from "react";
import { Button } from "@/components/ui/button";

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <Button onClick={() => setCount((n) => n + 1)}>
      Clicked {count} {count === 1 ? "time" : "times"}
    </Button>
  );
}

Press the button. useState(0) gives two things: the value as it is now, and a function that changes it.

const [count, setCount] = useState(0);

count;                          // 0: the value, as it is in this draw
setCount(5);                    // change it
setCount((n) => n + 1);         // change it from what it was

Use a value for a new state that doesn’t depend on the old one (setName("")), and a function when it does: setCount((n) => n + 1), setOpen((o) => !o), setTodos((list) => [...list, todo]). The function gets the value as it is when the change is made. Two clicks before the next draw both count, where setCount(count + 1) would count one.

Each part follows its state

import { useState } from "react";
import { Button } from "@/components/ui/button";

export default function App() {
  const [open, setOpen] = useState(true);
  const [count, setCount] = useState(3);
  return (
    <div className="grid gap-3">
      <p className={open ? "text-foreground" : "text-muted-foreground line-through"}>
        {count} of 10 tickets left
      </p>
      <div className="grid grid-cols-2 gap-2">
        <Button variant="secondary" disabled={!open || count === 0} onClick={() => setCount((n) => n - 1)}>Sell one</Button>
        <Button variant="secondary" onClick={() => setOpen((o) => !o)}>{open ? "Close" : "Open"} sales</Button>
      </div>
    </div>
  );
}

Work out the rest, don’t keep it

A value that follows from state is worked out while drawing, not kept as state of its own. Kept twice, the two drift apart the first time one is changed without the other.

import { useState } from "react";
import { Button } from "@/components/ui/button";

export default function App() {
  const [count, setCount] = useState(0);
  const double = count * 2;
  const big = count > 9;
  return (
    <Button className={big ? "text-lg" : ""} onClick={() => setCount((c) => c + 1)}>
      {count} × 2 = {double}
    </Button>
  );
}

When working it out is slow (a long list filtered and sorted), useMemo(() => …, [list, query]) keeps the result until what it was worked out from changes.

Several values that change together

Values that change together sit well in one object. Change it by making a new one: React compares by reference, so an object changed in place would not draw again.

import { useState } from "react";
import { Input } from "@/components/ui/input";

export default function App() {
  const [person, setPerson] = useState({ first: "Ada", last: "Lovelace" });
  return (
    <div className="grid gap-2">
      <Input aria-label="First name" value={person.first} onChange={(e) => setPerson({ ...person, first: e.target.value })} />
      <Input aria-label="Last name" value={person.last} onChange={(e) => setPerson({ ...person, last: e.target.value })} />
      <p className="text-sm text-muted-foreground">Hello, {person.first} {person.last}.</p>
    </div>
  );
}

{ ...person, first: … } copies the object with one field changed. A list works the same way: [...list, item] to add, list.filter((x) => x.id !== id) to take one away.

Next: show something only when a condition holds, in Showing and hiding.

View as Markdown