Code Reference

Counter

React · Example / how-to

Counter

React · Example / how-to


📋 Overview

A minimal counter with useState: increment, decrement, and reset in a single component.

🔧 Core concepts

PieceRole
useStateLocal numeric state
Event handlersUpdate on click
Functional updatessetCount(c => c + 1)
Derived UIRender current value

💡 Examples

Counter.tsx:

import { useState } from "react";

export function Counter({ initial = 0 }: { initial?: number }) {
  const [count, setCount] = useState(initial);

  return (
    <div>
      <p aria-live="polite">Count: {count}</p>
      <button type="button" onClick={() => setCount((c) => c - 1)}>

      </button>
      <button type="button" onClick={() => setCount(initial)}>
        Reset
      </button>
      <button type="button" onClick={() => setCount((c) => c + 1)}>
        +
      </button>
    </div>
  );
}

Usage:

import { Counter } from "./Counter";

export default function App() {
  return <Counter initial={0} />;
}

⚠️ Pitfalls

  • setCount(count + 1) in rapid clicks can stale — prefer functional updates.
  • Do not store derived values in state if they can be computed from count.
  • Keys on lists of counters must be stable if you mount many instances.

On this page