useCounter()

A simple abstraction to play with a counter, don't repeat yourself.

The Hook

1import { Dispatch, SetStateAction, useState } from 'react'
2
3interface ReturnType {
4 count: number
5 increment: () => void
6 decrement: () => void
7 reset: () => void
8 setCount: Dispatch<SetStateAction<number>>
9}
10
11function useCounter(initialValue?: number): ReturnType {
12 const [count, setCount] = useState(initialValue || 0)
13
14 const increment = () => setCount(x => x + 1)
15 const decrement = () => setCount(x => x - 1)
16 const reset = () => setCount(initialValue || 0)
17
18 return {
19 count,
20 increment,
21 decrement,
22 reset,
23 setCount,
24 }
25}
26
27export default useCounter

Usage

1import { useCounter } from 'usehooks-ts'
2
3export default function Component() {
4 const { count, setCount, increment, decrement, reset } = useCounter(0)
5
6 const multiplyBy2 = () => setCount((x: number) => x * 2)
7
8 return (
9 <>
10 <p>Count is {count}</p>
11 <button onClick={increment}>Increment</button>
12 <button onClick={decrement}>Decrement</button>
13 <button onClick={reset}>Reset</button>
14 <button onClick={multiplyBy2}>Multiply by 2</button>
15 </>
16 )
17}

Edit on CodeSandbox

See a way to make this page better?
Edit there »