* Counter hook * * @param {number} initialValue The initial value of the counter * @returns {handler} A handler to interact with the counter * @see https://rooks.vercel.app/docs/hooks/useCounter
(initialValue: number)
| 30 | * @see https://rooks.vercel.app/docs/hooks/useCounter |
| 31 | */ |
| 32 | function useCounter(initialValue: number): CounterHandler { |
| 33 | const [counter, setCounter] = useState(initialValue); |
| 34 | /** |
| 35 | * Increment counter by an amount |
| 36 | * |
| 37 | * @param {number} incrAmount |
| 38 | */ |
| 39 | const incrementBy = useCallback((incrAmount: number) => { |
| 40 | setCounter((currentCounter) => currentCounter + incrAmount); |
| 41 | }, []); |
| 42 | /** |
| 43 | * |
| 44 | * Decrement counter by an amount |
| 45 | * |
| 46 | * @param {*} decrAmount |
| 47 | */ |
| 48 | const decrementBy = useCallback( |
| 49 | (decrAmount: number) => { |
| 50 | incrementBy(-decrAmount); |
| 51 | }, |
| 52 | [incrementBy] |
| 53 | ); |
| 54 | |
| 55 | /** |
| 56 | * Increment counter by 1 |
| 57 | */ |
| 58 | const increment = useCallback(() => { |
| 59 | incrementBy(1); |
| 60 | }, [incrementBy]); |
| 61 | /** |
| 62 | * Decrement counter by 1 |
| 63 | */ |
| 64 | const decrement = useCallback(() => { |
| 65 | incrementBy(-1); |
| 66 | }, [incrementBy]); |
| 67 | /** |
| 68 | * Reset counter to initial value |
| 69 | */ |
| 70 | const reset = useCallback(() => { |
| 71 | setCounter(initialValue); |
| 72 | }, [initialValue]); |
| 73 | |
| 74 | return { |
| 75 | decrement, |
| 76 | decrementBy, |
| 77 | increment, |
| 78 | incrementBy, |
| 79 | reset, |
| 80 | value: counter, |
| 81 | }; |
| 82 | } |
| 83 | |
| 84 | export { useCounter }; |
no outgoing calls
searching dependent graphs…