ReactProps & stateLesson 32 / 69

useState

Exercise35 min

useState

State is memory a component owns:

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

The pattern is always the same: read state in the markup, change it only via the setter. The setter asks React to re-render with the new value; the component function runs again with fresh state.

Never mutate (count++) — React does not notice. And when the new value depends on the old, prefer the function form: setCount((c) => c + 1).

Exercise

Rebuild your click counter as a component with useState: count, plus a reset that calls setCount(0).

Practice in the diagram lab

This lesson's practice belongs in the diagram editor — design the schema you just read about, grade it against the solution, and save it to your account.

Open the diagram lab