useList
A custom React hook to manage and manipulate an array (list) with a variety of utility functions.> useList<T>(initialValue: T[]):
readonly [T[], {
append: (...items: T[]) => void;
apply: (callback: (value: T) => T) => void;
applyWhere: (condition: (item: T) => boolean, fn: (value: T) => T) => void;
filter: (fn: (value: T) => boolean) => void;
insert: (index: number, ...items: T[]) => void;
pop: () => void;
prepend: (...items: T[]) => void;
remove: (...indices: number[]) => void;
set: (...items: T[]) => void;
shift: () => void; }]
- initialValue: An array to initialize the list state with.
- Returns: A tuple containing the current list and an object with utility functions for manipulation.
Utility Functions
- append(...items: T[]): Adds new items to the end of the list.
- apply(callback: (value: T) => T): Applies a callback function to each item in the list.
- applyWhere(condition: (item: T) => boolean, fn: (value: T) => T): Applies a callback function to each item that matches the condition.
- filter(fn: (value: T) => boolean): Removes all items that do not match the condition.
- insert(index: number, ...items: T[]): Inserts items at a specific index.
- pop(): Removes the last item from the list.
- prepend(...items: T[]): Inserts items at the beginning of the list.
- remove(...indices: number[]): Removes items at specific indices.
- set(...items: T[]): Replaces the current list with the new items.
- shift(): Removes the first item from the list.
Example
import { useList } from "daily-toolset/hooks";
function ExampleComponent() {
const [list, { append, filter, remove, prepend }] = useList<number>([1, 2, 3]);
return (
<div>
<p>List: {list.join(", ")}</p>
<button onClick={() => append(4, 5)}>Append 4, 5</button>
<button onClick={() => prepend(0)}>Prepend 0</button>
<button onClick={() => filter((item) => item % 2 === 0)}>
Keep Even Numbers
</button>
<button onClick={() => remove(0)}>Remove First Item</button>
</div>
);
}
Use Cases
- Managing and updating stateful arrays in React components.
- Filtering, transforming, and dynamically modifying list items.
- Providing reusable utilities for working with arrays.