useCounter
Counter state management with increment, decrement, and reset operations. Perfect for React applications requiring numeric controls with Next.js integration and TypeScript support.
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
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
Prop | Type | Default | Description |
---|---|---|---|
initialValue | number | 0 | The starting value for the counter |
Return Value
Property | Type | Description |
---|---|---|
count | number | Current counter value |
increment | () => void | Increases count by 1 |
decrement | () => void | Decreases count by 1 |
reset | () => void | Resets count to initial value |
setCount | React.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
useCountdown
React hook that manages countdown functionality with configurable intervals, increment/decrement modes, and start/stop/reset controls.
useDarkMode
Manage dark mode state with OS preference detection and localStorage persistence. Perfect for React applications with Next.js integration and TypeScript support.