React: A counter with steps and undo

Keep a list of values in state, update it without changing it in place, and use it to undo.

What to build

A counter with selectable steps, a history and an undo button.

Requirements

  • Buttons 1, 5 and 10 choose the step; the chosen one has aria-pressed="true", and the step starts at 1.
  • Add and Subtract change the value by the step; the value starts at 0 and is shown in a p with the id value.
  • Every change is remembered. Undo goes back to the previous value, and is disabled when there is nothing to undo. A p with the id history shows all the values so far, separated by →.

Constraints

Do not modify state arrays in place.

Example

Choosing 5, pressing Add twice and Subtract once shows the value 5 and the history "0 → 5 → 10 → 5"; Undo then shows 10.

Why it works

Storing the whole history as an array makes undo a matter of dropping the last item, and making a new array each time is what lets React see the change.

Hints

Hint 1

Keep the history as an array in state: the current value is its last item.

Hint 2

Undo makes a new array without the last item: history.slice(0, -1).

Solution

Show one correct solution (try it yourself first)
import { useState } from "react";

const STEPS = [1, 5, 10];

export default function App() {
  const [step, setStep] = useState(1);
  const [history, setHistory] = useState([0]);
  const value = history[history.length - 1];

  return (
    <div>
      <div>
        {STEPS.map((s) => (
          <button key={s} aria-pressed={step === s} onClick={() => setStep(s)}>
            {s}
          </button>
        ))}
      </div>
      <p id="value">{value}</p>
      <button onClick={() => setHistory([...history, value + step])}>Add</button>
      <button onClick={() => setHistory([...history, value - step])}>Subtract</button>
      <button disabled={history.length === 1} onClick={() => setHistory(history.slice(0, -1))}>
        Undo
      </button>
      <p id="history">{history.join(" → ")}</p>
    </div>
  );
}

Lesson: State: a component's memory →