Created
January 6, 2022 21:36
-
-
Save chris-cornell/519932f86cdf82507c41d1b05b262651 to your computer and use it in GitHub Desktop.
some overly memoized hooks
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, useMemo, useCallback } from 'react'; | |
function getNextIndex(curr, len, shouldLoop) { | |
if (curr === len - 1) return shouldLoop ? 0 : curr; | |
return curr + 1; | |
} | |
function getPrevIndex(curr, len, shouldLoop) { | |
if (curr === 0) return shouldLoop ? len - 1 : 0; | |
return curr - 1; | |
} | |
/** Util hook to cycle through an array of n values */ | |
interface CyclerInput<T> { | |
values: T[]; | |
start?: number; | |
loop?: boolean; | |
} | |
export function useCycler<T>({ values = [], start = 0, loop = true }: CyclerInput<T>) { | |
const [index, setIndex] = useState(start); | |
const value = useMemo(() => values[index], [index]); | |
const { length } = values; | |
const nextIndex = getNextIndex(index, length, loop); | |
const nextValue = useMemo(() => values[nextIndex], [nextIndex]); | |
const prevIndex = getPrevIndex(index, length, loop); | |
const prevValue = useMemo(() => values[prevIndex], [prevIndex]); | |
const cycle = useCallback(() => setIndex(nextIndex), [nextIndex]); | |
const reverse = useCallback(() => setIndex(prevIndex), [prevIndex]); | |
return { | |
cycle, | |
reverse, | |
value, | |
nextValue, | |
prevValue, | |
}; | |
} |
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, useMemo, useCallback } from 'react'; | |
const getNextIndex = (curr) => { | |
if (curr) return 0; | |
return 1; | |
}; | |
/* Util hook to toggle between two generic values */ | |
interface TogglerInput<T> { | |
between: [T, T]; | |
start?: 0 | 1; | |
} | |
export function useToggler<T>({ between: types, start = 0 }: TogglerInput<T>) { | |
const [index, setIndex] = useState(start); | |
const value = useMemo(() => types[index], [index]); | |
const nextValue = useMemo(() => (index ? types[0] : types[1]), [index]); | |
const toggle = useCallback(() => setIndex(getNextIndex(index)), [index]); | |
return { | |
toggle, | |
value, | |
nextValue, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment