State
useCounter
Numeric counter with increment, decrement and reset.
Demo
live · imported from hookli
- count
- 0
import { useCounter } from "hookli";
export function Demo() {
const { count, increment, decrement, reset, setCount } = useCounter(0);
return (
<div>
<p>{count}</p>
<button onClick={decrement}>-1</button>
<button onClick={increment}>+1</button>
<button onClick={() => setCount(10)}>Set 10</button>
<button onClick={reset}>Reset</button>
</div>
);
}Usage
import { useCounter } from "hookli";
export function Demo() {
const { count, increment, decrement, reset, setCount } = useCounter(0);
return (
<div>
<p>{count}</p>
<button onClick={decrement}>-1</button>
<button onClick={increment}>+1</button>
<button onClick={() => setCount(10)}>Set 10</button>
<button onClick={reset}>Reset</button>
</div>
);
}API
useCounter(initialValue?: number): { count: number; increment: () => void; decrement: () => void; reset: () => void; setCount: Dispatch<SetStateAction<number>> }Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| initialValue | number | 0 | The count the hook starts from; reset returns here. |
Returns
| Name | Type | Description |
|---|---|---|
| count | number | The current count. |
| increment | () => void | Adds one to the count. |
| decrement | () => void | Subtracts one from the count. |
| reset | () => void | Restores the count to initialValue. |
| setCount | Dispatch<SetStateAction<number>> | Sets the count directly; accepts a value or an updater function. |
Hook
The implementation, straight from hookli. Copy it, or install the package.
import { Dispatch, SetStateAction, useCallback, useState } from "react";
export interface UseCounterReturn {
count: number;
increment: () => void;
decrement: () => void;
reset: () => void;
setCount: Dispatch<SetStateAction<number>>;
}
export const useCounter = (initialValue = 0): UseCounterReturn => {
const [count, setCount] = useState(initialValue);
const increment = useCallback(() => setCount((prev) => prev + 1), []);
const decrement = useCallback(() => setCount((prev) => prev - 1), []);
const reset = useCallback(() => setCount(initialValue), [initialValue]);
return { count, increment, decrement, reset, setCount };
};