Skip to content

Instantly share code, notes, and snippets.

@RodrigoNovais
Last active April 15, 2020 16:57
Show Gist options
  • Save RodrigoNovais/3a66b4222c113638962415d5310f6cfb to your computer and use it in GitHub Desktop.
Save RodrigoNovais/3a66b4222c113638962415d5310f6cfb to your computer and use it in GitHub Desktop.
Custom react hook to handle counters
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