useList
A React hook that manages an array as state. Provides efficient state management and stable action functions.
Interface
ts
function useList<T>(initialState: T[] = []): UseListReturn<T>;Parameters
- initialStateT[]
Initial array state.
Return Value
- UseListReturn<T>
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: 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<string>(['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();