useList
A React hook that manages an array as state. Provides efficient state management and stable action functions. Accepts mutable and readonly arrays for the initial state and setAll.
Interface
ts
function useList<T>(initialState: readonly T[] = []): UseListReturn<T>;Parameters
- initialStatereadonly T[]
Initial array state.
Return Value
- UseListReturn<T>
A tuple containing the array state and actions to manipulate it.
- listReadonlyArray<T>
The current array state.
- actions.push(value: T) => void
Appends a value to the end of the list.
- actions.insertAt(index: number, value: T) => void
Inserts a value at the specified index.
- actions.updateAt(index: number, value: T) => void
Updates the value at the specified index.
- actions.removeAt(index: number) => void
Removes the value at the specified index.
- actions.setAll(values: readonly T[]) => void
Replaces the entire list with a new array.
- actions.reset() => void
Resets the list to its initial state.
- listReadonlyArray<T>
Example
tsx
const [list, actions] = useList(['apple', 'banana']);
// Add an item
actions.push('cherry');
// Insert at index
actions.insertAt(1, 'grape');
// Update at index
actions.updateAt(0, 'orange');
// Remove at index
actions.removeAt(2);
// Replace all
actions.setAll(['kiwi', 'mango']);
// Reset to initial state
actions.reset();