Skip to content

useCycleOn

Cycle through a list of values.

The useCycleOn hook is helpful when you want to cycle through a list of items.

It provides with helper methods like forward, backward and reset to cycle in either directions or reset the cycle progress.

useCycleOn

Fruits List : 🍎,🍌,🍐,🍑

Current Fruit is : 🍎

Interact with the control to cycle through the fruits list

Usage

Import the hook from @abhushanaj/react-hooks and use in required component.

./src/App.tsx
import { useCycleOn } from '@abhushanaj/react-hooks';
function App() {
const [value, cycleControls] = useCycleOn(['🍎', '🍌', '🍐', '🍑']);
const { forward, backward, reset } = cycleControls;
return (
<div>
<p>Current: {value}</p>
<button onClick={forward}>Forward</button>
<button onClick={backward}>Backward</button>
<button onClick={reset}>Reset</button>
</div>
);
}
export default App;

Properties

  1. The forward() method starts from beginning again when the end of values list is reached.
  2. The backward() method starts from end again when the activeIndex reaches zero.

At no point is time will the activeIndex value return out of bounds index.

API Reference

Parameters

ParameterTypeDescriptionDefault
valuesArray<T>The values on which we need to cycle on.N/A

Return Value

ParameterTypeDescriptionDefault
valueTThe current value in the cycle.N/A
cycleControlsCycleControlsThe control options for the stack to add, remove etc.N/A

Types Reference

1. CycleControls

ParameterTypeDescriptionDefault
activeIndexnumberReturns the current activeIndex on the cycle.N/A
reset()=>voidResets the cycle back to the inital state,i.e activeIndex is reset to 0.N/A
forward()=>voidMove one step forward on the cycle.N/A
backward()=>voidMove one step backward on the cycle.N/A