Rooks
HooksState Management

useCounter

Manages a numeric counter with increment, decrement, and reset operations.

About

useCounter keeps a numeric value and exposes stable helpers for adding or subtracting one or an arbitrary amount. reset returns to the latest initialValue supplied by the component.

Examples

Basic counter controls

import { useCounter } from "rooks";

export default function App() {
  const { value, increment, decrement, incrementBy, decrementBy, reset } =
    useCounter(3);

  function incrementBy5() {
    incrementBy(5);
  }
  function decrementBy7() {
    decrementBy(7);
  }

  return (
    <>
      Current value is {value}
      <hr />
      <button type="button" onClick={increment}>
        Increment
      </button>
      <button type="button" onClick={decrement}>
        Decrement
      </button>
      <button type="button" onClick={incrementBy5}>
        Add 5
      </button>
      <button type="button" onClick={decrementBy7}>
        Subtract 7
      </button>
      <hr />
      <button type="button" onClick={reset}>
        Reset
      </button>
    </>
  );
}

Reset back to the initial value

import { useCounter } from "rooks";

export default function CounterWithReset() {
  const { value, incrementBy, decrementBy, reset } = useCounter(10);

  return (
    <div>
      <div>Current value: {value}</div>
      <button onClick={() => incrementBy(10)}>Add 10</button>
      <button onClick={() => decrementBy(4)}>Subtract 4</button>
      <button onClick={reset}>Reset to 10</button>
    </div>
  );
}

Parameters

ParameterTypeDefaultDescription
initialValuenumberRequiredInitial counter value and the value restored by reset().

Return value

Returns { value, increment, decrement, incrementBy, decrementBy, reset }. The four update helpers and reset return void; incrementBy and decrementBy accept any number, including negative or fractional values.

Behavior and lifecycle

Updates use functional React state setters, so multiple increments or decrements in one batch compose against the latest queued value. The update helpers have stable identities. reset is recreated when initialValue changes and restores that latest value. The hook creates no effects or external resources.

Compatibility and accessibility

The hook uses only React state and is safe during SSR. Give counter controls accessible names and expose the current value in visible text or an appropriate live region when changes must be announced.

On this page