Shadcn Hooks

useCounter

A hook that creates a counter.

Loading...

Installation

npx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-counter.json"
pnpm dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-counter.json"
yarn dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-counter.json"
bun x shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-counter.json"

Copy and paste the following code into your project.

use-counter.ts
import { useMemo, useReducer } from 'react'

function reducer(
  state: number,
  action:
    | { type: 'set'; payload: number | ((value: number) => number) }
    | { type: 'inc' }
    | { type: 'dec' },
) {
  switch (action.type) {
    case 'set':
      if (typeof action.payload === 'function') {
        return action.payload(state)
      }
      return action.payload
    case 'inc':
      return state + 1
    case 'dec':
      return state - 1
  }
}

export function useCounter(initialValue: number = 0) {
  const [count, dispatch] = useReducer(reducer, initialValue)

  return [
    count,
    useMemo(
      () => ({
        set: (value: number | ((value: number) => number)) =>
          dispatch({ type: 'set', payload: value }),
        inc: () => dispatch({ type: 'inc' }),
        dec: () => dispatch({ type: 'dec' }),
        reset: () => dispatch({ type: 'set', payload: initialValue }),
      }),
      [dispatch],
    ),
  ] as const
}

API

/**
 * A hook that creates a counter.
 * @param initialValue - The initial value of the counter
 * @returns A tuple containing the counter value and an object with the actions to increment, decrement, and reset the counter
 */
export function useCounter(initialValue: number = 0): readonly [
  number,
  {
    /**
     * Set the value of the counter
     * @param value - The value to set the counter to
     */
    set: (value: number | ((value: number) => number)) => void
    /**
     * Increment the value of the counter
     */
    inc: () => void
    /**
     * Decrement the value of the counter
     */
    dec: () => void
    /**
     * Reset the value of the counter to the initial value
     */
    reset: () => void
  },
]

Last updated on

On this page