Rehooks
Hooks

useCounter

A hook that returns a counter value and a function to increment or decrement the counter.

useCounter

A hook that returns a counter value and a function to increment or decrement the counter.

Usage

import { useCounter } from "rehooks-ts";
 
function Component() {
  const { count, increment, decrement, reset, setCount } = useCounter(0);
 
  function multiply(value: number) {
    setCount((prevCount) => prevCount * value);
  }
 
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
      <button onClick={() => reset()}>Reset</button>
      <button onClick={() => multiply(2)}>Multiply by 2</button>
    </div>
  );
}

API

useCounter

function useCounter(initialValue?: number): CounterReturnType;

Returns a counter value and a function to increment or decrement the counter.

Parameters

NameTypeDescription
initialValuenumberThe initial value of the counter. Default is 0.

Returns

NameTypeDescription
countnumberThe current value of the counter.
increment() => voidA function to increment the counter.
decrement() => voidA function to decrement the counter.
reset() => voidA function to reset the counter.
setCountDispatchA state setter function.

On this page