Hooks
No hooks found in any category.
useCounter
stateInstallation
npx usehooks-cli@latest add use-counter
Description
A simple and efficient React hook for managing counter state with increment, decrement, reset, and set operations.
Parameters
Name | Type | Default | Description |
---|---|---|---|
initialValue? | number | 0 | The initial value for the counter |
Return Type
UseCounterReturn
Property | Type | Description |
---|---|---|
count | number | The current counter value |
increment | () => void | Increment the counter by 1 |
decrement | () => void | Decrement the counter by 1 |
reset | () => void | Reset the counter to its initial value |
set | (value: number) => void | Set the counter to a specific value |
Examples
Basic Usage
Simple counter with increment and decrement
1const { count, increment, decrement, reset } = useCounter(0);
2
3return (
4 <div>
5 <p>Count: {count}</p>
6 <button onClick={increment}>+</button>
7 <button onClick={decrement}>-</button>
8 <button onClick={reset}>Reset</button>
9 </div>
10);
With Initial Value
Counter starting from a specific value
1const { count, increment, set } = useCounter(10);
2
3// Set to specific value
4const handleSetToHundred = () => set(100);
Dependencies
react
Notes
- •All mutation methods are memoized with useCallback for optimal performance
- •The reset function remembers the initial value passed to the hook
- •Safe to use in concurrent mode as it uses functional state updates
Implementation
1"use client";
2
3import { useState, useCallback } from "react";
4
5interface UseCounterReturn {
6 count: number;
7 increment: () => void;
8 decrement: () => void;
9 reset: () => void;
10 set: (value: number) => void;
11}
12
13export function useCounter(initialValue: number = 0): UseCounterReturn {
14 const [count, setCount] = useState(initialValue);
15
16 const increment = useCallback(() => setCount((x) => x + 1), []);
17 const decrement = useCallback(() => setCount((x) => x - 1), []);
18 const reset = useCallback(() => setCount(initialValue), [initialValue]);
19 const set = useCallback((value: number) => setCount(value), []);
20
21 return {
22 count,
23 increment,
24 decrement,
25 reset,
26 set,
27 };
28}
29