Rehooks

useCounter

Returns a tuple with counter value and increment, decrement, reset functions.

useCounter

Installation

npx rehooks-cli@latest add useCounter

Usage

Component.tsx
import { useCounter } from "~/hooks/useCounter";
 
function Component() {
  const [count, { increment, decrement, reset }] = useCounter(0);
 
  return (
    <div>
      <h2>Counter Example</h2>
      <p>Current Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}

API

useCounter

useCounter.ts
function useCounter(initialValue?: number): CounterReturnType;

Returns a tuple with counter value and increment, decrement, reset functions.

Parameters

NameTypeDescription
initialValue?numberOptional initial value of the counter. Defaults to 0.

Returns

NameTypeDescription
countnumberThe current value of the counter.
increment() => voidA function to increment the counter by 1.
decrement() => voidA function to decrement the counter by 1.
reset() => voidA function to reset the counter to the initial value.
setCountDispatchA function to set the counter to a new value.

On this page