useListStatestate
useListState
NewSSR SAFEManages array state with declarative helper methods for insertion, removal, reordering, and item transformations.
$ pnpm dlx shadcn@latest add @byphongphan/use-list-stateRequires
@byphongphan in components.jsonuse-list-state.tsx
Loading preview...
Installation
$ pnpm dlx shadcn@latest add @byphongphan/use-list-stateRequires
@byphongphan in components.jsonUsage
Interactive Todo List
Reordering List Items
Features
- Declarative Operations: Provides clean immutable handlers (
append,prepend,insert,remove,setItem) eliminating repetitive array slice and spread code. - Position Reordering: Move any item effortlessly using
.reorder({ from, to })or.swap({ from, to })with built-in boundary safety. - Granular Field Updates:
.setItemProp(index, prop, value)updates a specific property on an object item with complete TypeScript key checking. - Batch Transformers: Transform all items with
.apply(), target matching elements with.applyWhere(), or filter with.filter(). - Tuple Ergonomics: Returns a standard
[list, handlers]tuple matching React conventions.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
initialValue | T[] | (() => T[]) | [] | Initial array values or a lazy factory initializer. |
Returns
Returns a tuple [list, handlers]:
| Index / Property | Type | Description |
|---|---|---|
[0] (list) | T[] | The active array state. |
[1] (handlers) | ListStateHandlers<T> | Object containing all memoized array manipulation helpers. |
Handlers Methods
| Method | Description |
|---|---|
append(...items: T[]) | Appends one or more items to the end of the array. |
prepend(...items: T[]) | Prepends one or more items to the beginning of the array. |
insert(index: number, ...items: T[]) | Inserts one or more items at a specific index. |
remove(...indices: number[]) | Removes items at the specified index positions. |
reorder({ from, to }: ReorderPayload) | Moves an item from position from to position to. |
swap({ from, to }: ReorderPayload) | Swaps the positions of two items. |
setItem(index: number, item: T) | Replaces an entire item at index. |
setItemProp(index, prop, value) | Updates a single property of the object item at index. |
apply(fn: (item: T, idx: number) => T) | Maps through all items applying a transformer function. |
applyWhere(predicate, fn) | Transforms only items matching the predicate condition. |
filter(fn: (item: T, idx: number) => boolean) | Filters items according to a boolean predicate. |
setState(updater) | Direct React state setter for replacing the entire array. |