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. Defaults to an empty array.
Return Value
Returns a tuple [list, actions].
- 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.
Example
tsx
import { useList } from 'react-simplikit';
function TodoList() {
const [todos, actions] = useList<string>(['Buy milk', 'Walk the dog']);
return (
<div>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => actions.removeAt(index)}>Delete</button>
</li>
))}
</ul>
<button onClick={() => actions.push('New todo')}>Add</button>
<button onClick={() => actions.reset()}>Reset</button>
</div>
);
}