Last active
April 15, 2020 16:57
-
-
Save RodrigoNovais/3a66b4222c113638962415d5310f6cfb to your computer and use it in GitHub Desktop.
Custom react hook to handle counters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useCallback } from 'react' | |
export type Counter = { | |
count: number | |
increment: (value?: number | undefined) => void | |
decrement: (value?: number | undefined) => void | |
reset: (value?: number | undefined) => void | |
} | |
export default (initialValue: number = 0): Counter => { | |
const [count, setCounter] = useState<number>(initialValue) | |
const increment = useCallback((value?: number) => setCounter(currentcount => currentcount + (value ?? 1)), []) | |
const decrement = useCallback((value?: number) => setCounter(currentCount => currentCount - (value ?? 1)), []) | |
const reset = useCallback((value?: number) => setCounter(value || initialValue), [initialValue]) | |
return { count, increment, decrement, reset } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment