Last active
February 11, 2020 15:41
-
-
Save evan-moon/7bf2deb3bfadcc949092e89ea549b55a to your computer and use it in GitHub Desktop.
0 ~ max까지의 값을 무한하게 순환할 수 있는 카운터 훅
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 function useCircularCounter( | |
initialValue: number = 0, | |
max: number | |
): [number, () => void, () => void, () => void] { | |
const [value, setValue] = useState(initialValue); | |
const init = useCallback(() => setValue(0), []); | |
const increase = useCallback(() => { | |
setValue((value + 1) % max); | |
}, [max, value]); | |
const decrease = useCallback(() => { | |
const prevValue = value - 1; | |
const weight = Math.ceil(Math.abs(prevValue) / max) * max; | |
setValue((prevValue + weight) % max); | |
}, [max, value]); | |
return [value, init, increase, decrease]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment