Usage
use-list-state hook provides an API to work with list state:
const [values, handlers] = useListState([{ a: 1 }]);// add one or more items to the end of the listconst append = () => handlers.append({ a: 2 });// values -> [{ a: 1 }, { a: 2 }]// add one or more items to the start of the listconst prepend = () => handlers.prepend({ a: 3 }, { a: 4 });// values -> [{ a: 3 }, { a: 4 }, { a: 1 }, { a: 2 }]// remove items at given positionsconst remove = () => handlers.remove(0, 2);// values -> [{ a: 4 }, { a: 2 }]// insert one or more items at given positionconst insert = () => handlers.insert(1, { a: 5 });// values -> [{ a: 4 }, { a: 5 }, { a: 2 }]// apply function to each element of the listconst apply = () => handlers.apply((item, index) => ({ a: item.a * index }));// values -> [{ a: 0 }, { a: 5 }, { a: 4 }]// move item from one position to anotherconst reorder = () => handlers.reorder({ from: 2, to: 0 });// values -> [{ a: 4 }, { a: 0 }, { a: 5 }]// set entirely new stateconst setState = () => handlers.setState([{ a: 6 }, { a: 7 }]);// values -> [{ a: 6 }, { a: 7 }]// set individual item at given positionconst setItem = () => handlers.setItem(0, { a: 8 });// values -> [{ a: 8 }, { a: 7 }]// set item property at given positionconst setItemProp = () => handlers.setItemProp(1, 'a', 'new-prop');// values -> [{ a: 8 }, { a: 'new-prop' }]
API
use-list-state takes array as single argument and returns list values and handlers to change them in tuple, similar to react use-state hook.
Hook provides handlers to work with array data:
append
– add items to the end of the listprepend
– add items to the start of the listinsert
– insert items at given indexremove
– remove items at given indicesreorder
– move item from one position to anotherapply
– apply given function to all items in the listsetItem
– replace item at given indexsetItemProp
– set item property at given indexsetState
– set list state with react action
Indeterminate state checkbox example
TypeScript
Definition
function useListState<T>(initialValue: T[] = []): [T[],{setState: Dispatch<SetStateAction<T[]>>;append: (...items: T[]) => void;prepend: (...items: T[]) => void;insert: (index: number, ...items: T[]) => void;apply: (fn: (item: T, index?: number) => T) => void;remove: (...indices: number[]) => void;reorder: ({ from, to }: { from: number; to: number }) => void;setItem: (index: number, item: T) => void;setItemProp: <K extends keyof T, U extends T[K]>(index: number, prop: K, value: U) => void;}];
Set item type
By default use-list-state will use type from initialValues. If you init hook with empty array, you must specify item type:
useListState(['hello']); // ok, item type is stringuseListState([]); // not ok, item type is anyuseListState<string>([]); // ok, item type is string
Built by Vitaly Rtishchev and these awesome people