use-counter
shadcn-hooks/use-counterFreeHook
A hook that creates a counter.
Install it
npx shadcn@latest add https://shadcn-hooks.com/r/use-counter.jsonSource
1import { useMemo, useReducer } from 'react'23function reducer(4 state: number,5 action:6 | { type: 'set'; payload: number | ((value: number) => number) }7 | { type: 'inc' }8 | { type: 'dec' },9) {10 switch (action.type) {11 case 'set':12 if (typeof action.payload === 'function') {13 return action.payload(state)14 }15 return action.payload16 case 'inc':17 return state + 118 case 'dec':19 return state - 120 }21}2223export function useCounter(initialValue: number = 0) {24 const [count, dispatch] = useReducer(reducer, initialValue)2526 return [27 count,28 useMemo(29 () => ({30 set: (value: number | ((value: number) => number)) =>31 dispatch({ type: 'set', payload: value }),32 inc: () => dispatch({ type: 'inc' }),33 dec: () => dispatch({ type: 'dec' }),34 reset: () => dispatch({ type: 'set', payload: initialValue }),35 }),36 [dispatch],37 ),38 ] as const39}
Files it writes
More from shadcn-hooks
All 58 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| use-active-elementuse-active-element | shadcn-hooks | Hooks | Free | no deps | |
| use-batteryuse-battery | shadcn-hooks | Hooks | Free | no deps | |
| use-booleanuse-boolean | shadcn-hooks | Hooks | Free | no deps | |
| use-click-any-whereuse-click-any-where | shadcn-hooks | Hooks | Free | no deps | |
| use-click-awayuse-click-away | shadcn-hooks | Hooks | Free | no deps | |
| use-clipboarduse-clipboard | shadcn-hooks | Hooks | Free | no deps | |
| use-controllable-valueuse-controllable-value | shadcn-hooks | Hooks | Free | 1 dep | |
| use-creationuse-creation | shadcn-hooks | Hooks | Free | 1 dep |
