Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.2Remembering values with state

Local variables do not survive a render and changing them does not update the screen. State lets a component remember a value and ask React to render again when that value changes.

Declaring state

JSX
import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button
      className="counter__button"
      onClick={() => setCount(count + 1)}
    >
      Count: {count}
    </button>
  );
}

useState returns the current value and a setter. Calling the setter schedules another render; it does not change the value already captured by the current render.

Updating from previous state

When the next value depends on the previous one, give the setter an updater function: setCount(previous => previous + 1). React supplies the latest pending value, which matters when several updates occur together.

Rules of Hooks

Call Hooks only at the top level of a React component or a custom Hook. Do not call them inside conditions, loops or event handlers. React relies on the same Hooks being called in the same order on every render.

State is a render snapshot

Calling setCount does not rewrite count in the running handler. It requests a future render. That render calls the component again, and useState supplies the updated value. This is why logging state immediately after its setter often shows the old value.

State is private to a rendered component. Two Counter components have independent counts because each occupies its own position.

Challenge: build a step counter

Add state for a count and step size. Provide buttons to add and subtract the step, plus Reset. Render two copies and verify they change independently.

Extension

Make the step an input. event.target.value is a string, so convert it to a number before addition.

Feedback 👍
Comments are sent via email to me.