useCircularList

A React Hook that helps to create a circular list that can cycle through the list.

Tip

If you need to manage a state that toggle between two stable values, consider utilizing useToggle as an alternative.

Demo

Source
🍌 banner
🍎 apple
🍇 grape
🍉 watermelon
🍊 orange
Current:
[0] 🍌 banner

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

const [value, index, actions] = useCircularList<T>(initialList: T[], options)

Options

export interface UseCycleListOptions<T, R extends T = T> { /** * Initial value */ initialValue?: R /** * Fallback index when the value is not found */ fallbackIndex?: number /** * Custom function to get the index of the value * * @param {T} value - `T`, the value to find * @param {T[]} list - `T[]`, the list to search * @returns {number} `number`, the index of the value */ getIndexOf?: (value: T, list: T[]) => number }

Returns

export type UseCycleListReturnsActions<T> = { /** * Move to the next value * * @param {number} [step] - `number`, the step to move * @returns {T} `T`, the next value */ next: (step?: number) => T /** * Move to the previous value * * @param {number} [step] - `number`, the step to move * @returns {T} `T`, the previous value */ prev: (step?: number) => T /** * Move to the value at the specified index * * @param {number} index - `number`, the index to move * @returns {T} `T`, the value at the specified index */ go: (index: number) => T } export type UseCycleListReturns<T> = readonly [ /** * Current value */ state: T, /** * Actions to control the list */ UseCycleListReturnsActions<T>, /** * Current index */ index: number, ]