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

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