Hook with next, prev, and select that wraps around options
A toggle switches between two values. Many controls switch between more than two: a theme button that goes light → dark → system → light, a playback-speed button (1× → 1.5× → 2×), or a sort-direction header (none → ascending → descending). Implement a React hook, useCycle, that steps through a list of options and wraps around at the ends.
function useCycle<T>(options: T[], initialIndex?: number): {
value: T | undefined;
index: number;
next: () => void;
prev: () => void;
select: (option: T) => void;
}
options: the values to cycle through, in order. The values are unique (compared with ===).initialIndex: the index to start at. Defaults to 0.value is options[index].options[initialIndex]. If initialIndex is not a valid index of options (negative, too large, or not an integer), start at index 0.next() moves to the following option. From the last option it wraps to the first.prev() moves to the previous option. From the first option it wraps to the last.select(option) moves to that option. If option is not in options, nothing changes.next() twice in one click handler moves two steps.options as an inline array, so it is a new array on every render. next, prev and select must keep the same identity on every render, and an inline array must not cause extra renders or loops.options changes, keep the current value if it is still in the list (its index may change). If it was removed, go to the first option.options is empty, value is undefined, index is -1, and the actions do nothing.function ThemeButton() {
const { value, next } = useCycle(['light', 'dark', 'system']);
return <button onClick={next}>Theme: {value}</button>;
}
// value: 'light' -> next() -> 'dark' -> next() -> 'system' -> next() -> 'light'
const speed = useCycle([1, 1.5, 2], 1);
// speed.value === 1.5, speed.index === 1
speed.prev(); // 1
speed.prev(); // 2 (wrapped)
speed.select(1.5); // 1.5
speed.select(3); // still 1.5: 3 is not an option
// options change from ['a', 'b', 'c'] (value 'c') to ['c', 'a']: value 'c', index 0
// options change from ['c', 'a'] (value 'c') to ['a', 'b']: value 'a', index 0
ReactDOM.flushSync.Object.assign(window, { useCycle }); below “Do not edit below this line”. The tests use it to call your hook.