Skip to content

use-counter

A Hook for Fun

A type-safe React hook for managing counter state with customizable step values and dynamic property naming.

Features

  • Find out yourself buddy

Parameters

ParameterTypeRequiredDefault ValueDescription
keystring""Prefix for generated property names. Creates type-safe object properties.
propsobjectundefinedConfiguration object containing initialValue and stepper.
initialValuenumber0Initial value for the counter.
steppernumber1Amount to increment/decrement by on each operation.

Returns

Returns a type-safe object with dynamically named properties:

Without key (default):

  • counter: number - Current counter value
  • incrementCounter: () => void - Function to increment counter
  • decrementCounter: () => void - Function to decrement counter

With key (e.g., "user"):

  • userCounter: number - Current counter value
  • incrementUserCounter: () => void - Function to increment counter
  • decrementUserCounter: () => void - Function to decrement counter

Usage Examples

Basic Counter

ts
import { useCounter } from 'classic-react-hooks'

export default function YourComponent() {
   const { counter, decrementCounter, incrementCounter } = useCounter()

   // If key is passed then properties within the object is prefixed with it.
   // const { userCounter, incrementUserCounter, decrementUserCounter } = useCounter("user")

   return (
      <div>
         <div>
            <button onClick={decrementCounter}>decrement</button>
            <p>{counter}</p>
            <button onClick={incrementCounter}>increment</button>
         </div>
      </div>
   )
}

Named Counter with Custom Step

ts
import { useCounter } from 'classic-react-hooks'

export default function UserScoreCounter() {
   const { userCounter, incrementUserCounter, decrementUserCounter } = useCounter('user', {
      initialValue: 10,
      stepper: 5,
   })

   return (
      <div>
         <h3>User Score: {userCounter}</h3>
         <button onClick={decrementUserCounter}>-5</button>
         <button onClick={incrementUserCounter}>+5</button>
      </div>
   )
}