Skip to content

State: A Component's Memory

The Course
•
20 min study

Clicking can run code. Now make the page change when you click. The obvious idea is a variable that the handler updates. Try it.

Why a plain variable doesn't work

Click Add 5 minutes a few times. Watch the heading and the console.

A plain variable React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); export default function App() { let minutes = 0; function addFive() { minutes = minutes + 5; console.log("minutes is now", minutes); } return ( <main> <h1>Minutes studied: {minutes}</h1> <button onClick={addFive}>Add 5 minutes</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

The console says the number goes up: 5, 10, 15. The heading stays at Minutes studied: 0. There are two separate problems:

  1. Changing a variable doesn't tell React anything. React shows a component by calling its function and using the JSX it returns. Nothing calls App again after a click, so the heading isn't rebuilt.

  2. Even if React called App again, it would start from scratch. The first line of App is let minutes = 0. Every call creates a new minutes, set to 0:

    JSX
    export default function App() {
      let minutes = 0;
    
      function addFive() {
        minutes = minutes + 5;
        console.log("minutes is now", minutes);
      }
    
      return (
        <main>
          <h1>Minutes studied: {minutes}</h1>
          <button onClick={addFive}>Add 5 minutes</button>
        </main>
      );
    }

So you need a value that survives between calls, and a way to tell React to call the component again. That's what state is for.

useState

JavaScript
import { useState } from "react";

const [minutes, setMinutes] = useState(0);
  • useState(0) creates a piece of state whose starting value is 0.
  • It returns two things in an array, and the brackets on the left unpack them:
    • minutes: the current value.
    • setMinutes: a function that changes the value and asks React to show the component again.
  • Name them as a pair: something and setSomething.
The same page, with state React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function App() { const [minutes, setMinutes] = useState(0); function addFive() { setMinutes(minutes + 5); } return ( <main> <h1>Minutes studied: {minutes}</h1> <button onClick={addFive}>Add 5 minutes</button>{" "} <button onClick={() => setMinutes(0)}>Reset</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Click Add 5 minutes and Reset. Each click calls setMinutes. React remembers the new value, calls App again, and this time useState returns the remembered value instead of 0. The 0 is used only the very first time.

Showing a component again with new values is called a re-render.

Hooks

Functions whose names start with use, like useState, are called hooks. They only work at the top level of a component: not inside an if, a loop, or a handler. React tells hooks apart by the order they're called in, so that order must be the same on every render.

Predict

setMinutes asks for a new render, but it doesn't change minutes in the middle of the current one. Add a log line to addFive:

JavaScript
function addFive() {
  setMinutes(minutes + 5);
  console.log("minutes right after setMinutes:", minutes);
}

Click once. What does the console show: 0 or 5?

Check your prediction

0. minutes is the value for this render, like a photo of it. The new value, 5, arrives in the next render, when React calls App again. The next lesson explores this.

Your turn

Exercise

A goal counter

Add a second button, Remove 5 minutes, that subtracts 5. It must never let minutes go below 0. Disable it when minutes is already 0.

Your working space React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function App() { const [minutes, setMinutes] = useState(0); function addFive() { setMinutes(minutes + 5); } return ( <main> <h1>Minutes studied: {minutes}</h1> <button onClick={addFive}>Add 5 minutes</button>{" "} <button onClick={() => setMinutes(0)}>Reset</button> </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

There are two guards. The new value must never be below 0, so you want "the larger of 0 and minutes - 5" (JavaScript's Math object has a function for the larger of two numbers). And the button itself can be switched off: which HTML attribute stops a button being clicked?

Hint 2: a first step

Start with onClick={() => setMinutes(minutes - 5)} and click it at 0: the page shows -5 minutes. That's the bug the guards prevent. Fix the new value first, check that clicking at 0 now stays at 0, then add the attribute that greys the button out. It takes a true or false value.

Show one solution
JSX
<button onClick={() => setMinutes(Math.max(0, minutes - 5))} disabled={minutes === 0}>
  Remove 5 minutes
</button>

With disabled, the button can't be clicked when minutes is 0. Math.max still guards against going below 0 if the button is ever enabled by mistake.

Was this article helpful?

Your response is saved on this device.