Skip to content

useCycleList

Category
Export Size
422 B
Last Changed
5 days ago

Cycle through a list of items

Demo

Usage

ts
import { 
useCycleList
} from '@reause/core'
const {
state
,
next
,
prev
,
go
} =
useCycleList
([
'Dog', 'Cat', 'Lizard', 'Shark', 'Whale', 'Dolphin', 'Octopus', 'Seal', ])
console
.
log
(
state
) // 'Dog'
prev
()
console
.
log
(
state
) // 'Seal'
go
(3)
console
.
log
(
state
) // 'Shark'

Source Forms

list is a read-only value source and takes a plain T[] (upstream: MaybeRefOrGetter<T[]>). Resolve a React ref or state value at the call site:

tsx
const [
list
,
setList
] =
useState
(['Dog', 'Cat'])
const {
state
,
next
} =
useCycleList
(
list
) // a new array is picked up on re-render
const {
state
:
refState
} =
useCycleList
(listRef.current) // resolve a React ref yourself

Type Declarations

ts
export interface UseCycleListOptions<T> {
    initialValue?: T;
    fallbackIndex?: number;
    getIndexOf?: (value: T, list: T[]) => number;
}

export interface UseCycleListReturn<T> {
    state: T;
    index: number;
    next: (n?: number) => T;
    prev: (n?: number) => T;
    go: (i: number) => T;
    setState: Dispatch<SetStateAction<T>>;
    setIndex: Dispatch<SetStateAction<number>>;
}

export function useCycleList<T>(list: T[], options?: UseCycleListOptions<T>): UseCycleListReturn<T>

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
36c84 - fix(core): resolve useCycleList audit findings (#537)
8fddc - chore!: remove all Vue-only Maybe* types and getter unions, adopt React Ref (#462)

Released under the MIT License. v0.1.8