Join our Discord Community

useCounter

Counter state management with increment, decrement, and reset operations. Perfect for React applications requiring numeric controls with Next.js integration and TypeScript support.

Loading component...

Installation

npx shadcn@latest add https://www.shadcn.io/registry/use-counter.json
npx shadcn@latest add https://www.shadcn.io/registry/use-counter.json
pnpm dlx shadcn@latest add https://www.shadcn.io/registry/use-counter.json
bunx shadcn@latest add https://www.shadcn.io/registry/use-counter.json

Features

  • Complete counter operations with increment, decrement, reset, and direct state access
  • Flexible initial values supporting any numeric starting point with optional parameters
  • Optimized callbacks using React.useCallback for performance in complex component trees
  • TypeScript support with comprehensive type definitions and IntelliSense integration
  • Memory efficient with memoized functions preventing unnecessary re-renders
  • Custom operations through direct setCount access for complex mathematical operations

Examples

Game Stats Dashboard

Loading component...

Advanced implementation showing multiple counter instances, custom operations, and complex state management patterns.

Use Cases

This free open source React hook works well for:

  • Game interfaces - Score tracking, lives, and multipliers built with Next.js and TypeScript
  • Shopping carts - Quantity controls with shadcn/ui component integration
  • Form inputs - Numeric steppers using React state management patterns
  • Dashboard counters - Statistics and metrics with Tailwind CSS styling
  • Inventory systems - Stock management for JavaScript-based applications
  • Analytics displays - Real-time counters with automatic increment/decrement functionality

API Reference

useCounter

PropTypeDefaultDescription
initialValuenumber0The starting value for the counter

Return Value

PropertyTypeDescription
countnumberCurrent counter value
increment() => voidIncreases count by 1
decrement() => voidDecreases count by 1
reset() => voidResets count to initial value
setCountReact.Dispatch<React.SetStateAction<number>>Direct state setter for custom operations

Implementation Notes

  • All callback functions are memoized using React.useCallback for optimal performance
  • The reset function always returns to the originally provided initialValue
  • setCount accepts both direct values and updater functions for flexible state management
  • Hook is fully compatible with React Strict Mode and Next.js server-side rendering
  • Custom operations can be implemented using setCount with updater functions like (prev) => prev * 2