useCounter()
A simple abstraction to play with a counter, don't repeat yourself.
The Hook
1import { Dispatch, SetStateAction, useState } from 'react'23interface ReturnType {4 count: number5 increment: () => void6 decrement: () => void7 reset: () => void8 setCount: Dispatch<SetStateAction<number>>9}1011function useCounter(initialValue?: number): ReturnType {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 React from 'react'23import { useCounter } from 'usehooks-ts'45export default function Component() {6 const { count, setCount, increment, decrement, reset } = useCounter(0)78 const multiplyBy2 = () => setCount(x => x * 2)910 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 »