useList
State & dataA React hook for managing array state with immutable updates
Install
$ npm install @usefy/use-listQuick start
useList.tsx
import { useList } from "@usefy/use-list";
interface Todo {
id: number;
text: string;
completed: boolean;
}
function TodoApp() {
const [todos, { push, removeAt, updateAt }] = useList<Todo>([]);
const addTodo = (text: string) =>
push({ id: Date.now(), text, completed: false });
const toggleTodo = (index: number) => {
const todo = todos[index];
updateAt(index, { ...todo, completed: !todo.completed });
};
return (
<ul>
{todos.map((todo, i) => (
<li key={todo.id}>
<input
type="checkbox"
checked={todo.completed}
onChange={() => toggleTodo(i)}
/>
{todo.text}
<button onClick={() => removeAt(i)}>×</button>
</li>
))}
</ul>
);
}API reference
useList<T>(initialState?)
Returns a tuple of the current read-only list and a stable actions object.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
initialState | ListInitializer<T> | empty | An array/iterable of items, or a factory returning one (evaluated once) |
Returns [list, actions]
| Item | Type | Description |
|---|---|---|
list | readonly T[] | Current list. Read via index, map, iteration |
actions | UseListActions<T> | Stable action handlers (see below) |
Actions
| Action | Signature | Description |
|---|---|---|
set | (next: T[] | ((prev: readonly T[]) => T[])) => void | Replace the whole list, by value or updater |
push | (...items: T[]) => void | Append one or more items |
filter | (predicate: (item: T, index: number) => boolean) => void | Keep only matching items (no-op if nothing removed) |
sort | (compareFn?: (a: T, b: T) => number) => void | Sort immutably (the current list is not mutated) |
clear | () => void | Remove all items (no-op if already empty) |
removeAt | (index: number) => void | Remove the item at index (no-op if out of range) |
insertAt | (index: number, ...items: T[]) => void | Insert item(s) at index (index clamped to [0, length]) |
updateAt | (index: number, item: T) => void | Replace the item at index (no-op if out of range or unchanged) |
reset | () => void | Restore the initial items (a fresh copy) |
The returned
listisreadonly T[], so callinglist.push(...)directly is a TypeScript error. Use the actions — mutating the array in place would bypass React state and break re-renders.
Go deeper
This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.