Fullstack CourseLearn by building

react · source-driven

State: a component’s memory

Components need to remember information across renders. useState is that memory — a regular let variable is not.

You will learn

  • How to add a state variable with the useState Hook
  • What pair of values useState returns
  • How to add more than one state variable
  • Why state is called local

When a regular variable isn’t enough

The React docs open with a gallery where let index = 0 increments on click — but the screen never updates. Mutating a local variable does not ask React to render again.

Try it (this is intentionally broken)

Homenaje a la Neurocirugía by Marta Colvin Andrade

(1 of 3) — UI stuck on 1 because let index is not state.

Although Colvin is predominantly known for abstract themes, this homage to neurosurgery is one of her most recognizable public pieces.

let index = 0;

function handleClick() {
  index = index + 1; // changes the variable…
  // …but React does not know it should re-render
}

Add a state variable with useState

import { useState } from 'react';

const [index, setIndex] = useState(0);

function handleClick() {
  setIndex(index + 1);
}

You get the current state and a setter. Calling the setter queues a re-render with the new value — that is the whole point.

Working gallery (docs pattern)

Homenaje a la Neurocirugía by Marta Colvin Andrade

(1 of 3)

Although Colvin is predominantly known for abstract themes, this homage to neurosurgery is one of her most recognizable public pieces.

State is local

If you render the same component twice, each instance gets its own state. Click each button separately — from the docs’ “counters that update separately” example:

Try it

Recap

  • useState declares component memory
  • Calling the setter triggers a re-render
  • State is local to a component instance
  • Hooks like useState must be called at the top level

Challenge

Try this

Add a second state variable showMore (boolean). A button toggles whether the sculpture description is visible — same dual-state pattern as the docs’ gallery with “Show details”.