useCounter()
A simple abstraction to play with a counter, don't repeat yourself.
The Hook
1import { Dispatch, SetStateAction, useState } from 'react'23interface UseCounterOutput {4 count: number5 increment: () => void6 decrement: () => void7 reset: () => void8 setCount: Dispatch<SetStateAction<number>>9}1011function useCounter(initialValue?: number): UseCounterOutput {12 const [count, setCount] = useState(initialValue || 0)1314 const increment = () => setCount(x => x + 1)15 const decrement = () => setCount(x => x - 1)16 const reset = () => setCount(initialValue || 0)1718 return {19 count,20 increment,21 decrement,22 reset,23 setCount,24 }25}2627export default useCounter
Usage
1import { useCounter } from 'usehooks-ts'23export default function Component() {4 const { count, setCount, increment, decrement, reset } = useCounter(0)56 const multiplyBy2 = () => setCount((x: number) => x * 2)78 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}
See a way to make this page better?
Edit there »