Hook cycling through values forward or backward by n steps
A video player has a speed button that goes 1× → 1.25× → 1.5× → 2× → 1×. A carousel steps through slides and can jump several slides at once. A map toggles between “road”, “satellite” and “terrain”. All of them rotate through a fixed set of values. Implement a React hook, useRotation, that takes the values as arguments and returns the current one plus a function that rotates forward or backward by any number of steps.
function useRotation<T>(...values: T[]): [current: T | undefined, rotate: (step?: number | React.SyntheticEvent) => void]
values: the values to rotate through, in order, passed as separate arguments. Values may repeat.useState: the current value and rotate.0).rotate() moves one position forward. From the last value it wraps to the first.rotate(step) with an integer step moves step positions. A negative step moves backward. Any size wraps around: with 3 values, rotate(4) moves the same as rotate(1), and rotate(-1) from the first value lands on the last.step is a number that is not an integer (1.5, NaN, Infinity), nothing changes. rotate(0) changes nothing either.step is not a number at all, treat it as rotate(). This lets callers write <button onClick={rotate}>: React passes the click event, and the button moves one step.rotate() and then rotate(2) in one click handler moves three positions.rotate must keep the same identity on every render.position % values.length.current is undefined and rotate does nothing. If values are passed later, start at the first one.function SpeedButton() {
const [speed, rotate] = useRotation(1, 1.25, 1.5, 2);
return <button onClick={rotate}>{speed}×</button>;
}
// 1 -> click -> 1.25 -> click -> 1.5 -> click -> 2 -> click -> 1
const [layer, rotate] = useRotation('road', 'satellite', 'terrain');
rotate(-1); // 'terrain' (wrapped backward)
rotate(5); // 'satellite' (5 steps forward from position 2 is position 1)
rotate(0.5); // still 'satellite'
rotate(); rotate(); // same event: 'road'
// Position 4 of ('xs', 's', 'm', 'l', 'xl') is 'xl'.
// The next render passes ('red', 'green', 'blue'): position 4 % 3 = 1, so current is 'green'.
rotate inside ReactDOM.flushSync, sometimes several times in one call, and re-renders with different values.rotate straight to a button’s onClick and clicks it.Object.assign(window, { useRotation }); below “Do not edit below this line”. The tests use it to call your hook.