Skip to content

Latest commit

 

History

History
120 lines (104 loc) · 2.85 KB

File metadata and controls

120 lines (104 loc) · 2.85 KB

useCounter

useCounter is a React hook that manages a numeric counter state with increment, decrement, and reset capabilities. Optionally, you can provide minimum and maximum values to constrain the counter's range.

Interface

function useCounter(options?: UseCounterOptions): UseCounterReturn;

type UseCounterOptions = {
  initialValue?: number;
  min?: number;
  max?: number;
  step?: number;
};

type UseCounterReturn = {
  count: number;
  increment: () => void;
  decrement: () => void;
  reset: () => void;
  setCount: (value: number | ((prev: number) => number)) => void;
};

Parameters

Return Value

Example

import { useCounter } from 'react-simplikit';

function ShoppingCart() {
  const { count, increment, decrement, reset } = useCounter({
    initialValue: 1,
    min: 1,
    max: 10,
  });

  return (
    <div>
      <span>Quantity: {count}</span>
      <button type="button" onClick={decrement}>-</button>
      <button type="button" onClick={increment}>+</button>
      <button type="button" onClick={reset}>Reset</button>
    </div>
  );
}

Constraints

The hook automatically ensures that the counter stays within the specified bounds:

  • When incrementing beyond max, the value will stay at max
  • When decrementing below min, the value will stay at min
  • When using setCount, any value outside the bounds will be adjusted to the nearest boundary