API Reference
useTimedCounter

useTimedCounter

The useTimedCounter hook provides a simple way to create a timed counter that increments at regular intervals. This hook is particularly useful for scenarios where you need to display and manage a counter that can start, stop, and reset based on specified conditions.

Installation

  1. Make sure you have @ridgehkr/useful installed in your application. If not, you can get started by following the installation instructions.

  2. Import useTimedCounter into your component.

import { useTimedCounter } from '@ridgehkr/useful'

Example

This is a basic example where useTimedCounter is used to manage the current index of the counter, incrementing automatically every 1000ms. The counter will loop back to its initial index of 1 when it reaches 10.

TestTimer.tsx
import { useTimedCounter } from '@ridgehkr/useful'
 
function TestTimer() {
  const { index, pause, play, reset, goToIndex, running } = useTimedCounter(
    1,
    10,
    1000,
    true
  )
 
  return (
    <div>
      <p>Current Index: {index}</p>
      <button onClick={running ? pause : play}>
        {running ? 'Pause' : 'Play'}
      </button>
      <button onClick={reset}>Reset</button>
      <button onClick={() => goToIndex(5)}>Go to Index 5</button>
    </div>
  )
}

API Reference

Hook Signature

useTimedCounter(
  initialValue: number,
  maxValue: number,
  interval: number,
  loop: boolean
): TimedCounterState

Parameters

PropertyTypeDefaultDescription
initialValuenumber(required)The initial value of the counter
maxValuenumber(required)The maximum value of the counter.
intervalnumber(required)The counter increment interval in milliseconds.
loopbooleanfalseIndicates whether the counter should loop back to initialValue when the maximum value is reached.

Return Value

The useTimedCounter hook returns a TimedCounterState object with the following properties:

PropertyTypeDescription
indexnumberThe current index of the counter
pause() => voidA function to pause the counter
play() => voidA function to play the counter
reset() => voidA function to reset the counter to initialValue
goToIndex(index: number) => voidA function to set the counter to a specific index
runningbooleanIndicates whether the counter is currently running