React: A counter that cannot go below zero

Give a component its first piece of state.

What to build

A counter with plus, minus and reset buttons.

Requirements

  • Show the count in a p with the id count, starting at 0.
  • Buttons +1, -1 and Reset change it; the count never goes below 0.

Constraints

Use useState.

Example

Pressing +1 twice and -1 once shows 1; pressing -1 at 0 keeps 0.

Why it works

The state value survives each render, and every call to its setter makes React show the new number.

Hints

Hint 1

const [count, setCount] = useState(0);

Hint 2

The minus button can use Math.max(0, count - 1).

Solution

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

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p id="count">{count}</p>
      <button onClick={() => setCount(count + 1)}>+1</button>
      <button onClick={() => setCount(Math.max(0, count - 1))}>-1</button>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

Lesson: State: a component's memory →