Skip to content

Instantly share code, notes, and snippets.

@chris-cornell
Created January 6, 2022 21:36
Show Gist options
  • Save chris-cornell/519932f86cdf82507c41d1b05b262651 to your computer and use it in GitHub Desktop.
Save chris-cornell/519932f86cdf82507c41d1b05b262651 to your computer and use it in GitHub Desktop.
some overly memoized hooks
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,
};
}
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