useCounter


A simple abstraction to play with a counter, don't repeat yourself.

Usage

import { useCounter } from 'reactchemy'

export default function Component() {
   const { count, setCount, increment, decrement, reset } = useCounter(0)

   const multiplyBy2 = () => setCount((x: number) => x * 2)

   return (
    <>
      <p>Count is {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
      <button onClick={reset}>Reset</button>
      <button onClick={multiplyBy2}>Multiply by 2</button>
    </>
   )
}

Hook

import type { Dispatch, SetStateAction } from 'react'
import { useState } from 'react'

interface UseCounterOutput {
   count: number
   increment: () => void
   decrement: () => void
   reset: () => void
   setCount: Dispatch<SetStateAction<number>>
}

export function useCounter(initialValue?: number): UseCounterOutput {
   const [count, setCount] = useState(initialValue || 0)

   const increment = () => setCount(x => x + 1)
   const decrement = () => setCount(x => x - 1)
   const reset = () => setCount(initialValue || 0)

   return {
      count,
      increment,
      decrement,
      reset,
      setCount,
   }
}