Skip to content

Instantly share code, notes, and snippets.

@evan-moon
Last active February 11, 2020 15:41
Show Gist options
  • Save evan-moon/7bf2deb3bfadcc949092e89ea549b55a to your computer and use it in GitHub Desktop.
Save evan-moon/7bf2deb3bfadcc949092e89ea549b55a to your computer and use it in GitHub Desktop.
0 ~ max까지의 값을 무한하게 순환할 수 있는 카운터 훅
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