Skip to main content

useList

The useList hook manages an array as React state and gives you the common operations — push, insert, update, remove, filter — as stable functions. Every change produces a new array, so it works correctly in dependency arrays and with React.memo.

Usage​

Installation​

import { useList } from "hookstorm";

Parameters​

  • initialList — (optional) The initial items.

Return Values​

  • list — The current array. Treat it as read-only and update it through the actions below.
  • set(list) — Replaces the whole list.
  • push(...items) — Appends one or more items.
  • insertAt(index, item) — Inserts an item at an index.
  • updateAt(index, item) — Replaces the item at an index.
  • removeAt(index) — Removes the item at an index.
  • filter(predicate) — Keeps only the items for which predicate(item, index) returns true.
  • clear() — Removes all items.
  • reset() — Restores the initial items.

Example Usage​

import { ReactElement, useState } from "react";
import { useList } from "hookstorm";

export default function ShoppingList(): ReactElement {
const { list, push, removeAt, clear } = useList<string>(["Milk"]);
const [text, setText] = useState("");

return (
<div>
<ul>
{list.map((item, index) => (
<li key={index}>
{item} <button onClick={() => removeAt(index)}>Remove</button>
</li>
))}
</ul>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button
onClick={() => {
push(text);
setText("");
}}
>
Add
</button>
<button onClick={clear}>Clear</button>
</div>
);
}

Notes​

  • Indexes outside the list are ignored: insertAt accepts 0 to list.length, while updateAt and removeAt accept 0 to list.length - 1. The state does not change in that case, so there is no re-render.
  • Action functions have a stable identity, so they are safe to pass to memoized children.
  • reset uses the items from the first render; later changes to initialList are ignored.