mirror of
https://github.com/streamich/react-use.git
synced 2025-12-08 18:02:14 +00:00
2.4 KiB
2.4 KiB
useStateList
Provides handles for circular iteration over states list.
Supports forward and backward iterations and arbitrary position set.
Usage
import { useStateList } from 'react-use';
import { useRef } from 'react';
const stateSet = ['first', 'second', 'third', 'fourth', 'fifth'];
const Demo = () => {
const { state, prev, next, setStateAt, setState, currentIndex, isFirst, isLast } = useStateList(stateSet);
const indexInput = useRef<HTMLInputElement>(null);
const stateInput = useRef<HTMLInputElement>(null);
return (
<div>
<pre>
{state} [index: {currentIndex}], [isFirst: {isFirst}], [isLast: {isLast}]
</pre>
<button onClick={() => prev()}>prev</button>
<br />
<button onClick={() => next()}>next</button>
<br />
<input type="text" ref={indexInput} style={{ width: 120 }} />
<button onClick={() => setStateAt((indexInput.current!.value as unknown) as number)}>set state by index</button>
<br />
<input type="text" ref={stateInput} style={{ width: 120 }} />
<button onClick={() => setState(stateInput.current!.value)}> set state by value</button>
</div>
);
};
Reference
const { state, currentIndex, prev, next, setStateAt, setState, isFirst, isLast } = useStateList<T>(stateSet: T[] = []);
If stateSet changed, became shorter than before and currentIndex left in shrunk gap - the last element of list will be taken as current.
state: T— current state value;currentIndex: number— current state index;prev(): void— switches state to the previous one. If first element selected it will switch to the last one;next(): void— switches state to the next one. If last element selected it will switch to the first one;setStateAt(newIndex: number): void— set the arbitrary state by index. Indexes are looped, and can be negative.
4ex: if list contains 5 elements, attempt to set index 9 will bring use to the 5th element, in case of negative index it will start counting from the right, so -17 will bring us to the 4th element.setState(state: T): void— set the arbitrary state value that exists instateSet. In case new state does not exists instateSetan Error will be thrown.isFirst: boolean—trueif current state is the first one.isLast: boolean—trueif current state is the last one.