Skip to content
usefy

useList

State & data

A React hook for managing array state with immutable updates

Install

$ npm install @usefy/use-list

Quick 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

ParameterTypeDefaultDescription
initialStateListInitializer<T>emptyAn array/iterable of items, or a factory returning one (evaluated once)

Returns [list, actions]

ItemTypeDescription
listreadonly T[]Current list. Read via index, map, iteration
actionsUseListActions<T>Stable action handlers (see below)

Actions

ActionSignatureDescription
set(next: T[] | ((prev: readonly T[]) => T[])) => voidReplace the whole list, by value or updater
push(...items: T[]) => voidAppend one or more items
filter(predicate: (item: T, index: number) => boolean) => voidKeep only matching items (no-op if nothing removed)
sort(compareFn?: (a: T, b: T) => number) => voidSort immutably (the current list is not mutated)
clear() => voidRemove all items (no-op if already empty)
removeAt(index: number) => voidRemove the item at index (no-op if out of range)
insertAt(index: number, ...items: T[]) => voidInsert item(s) at index (index clamped to [0, length])
updateAt(index: number, item: T) => voidReplace the item at index (no-op if out of range or unchanged)
reset() => voidRestore the initial items (a fresh copy)

The returned list is readonly T[], so calling list.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.

More in state & data