State Management
useArrayState
About
A comprehensive array state manager hook for React that provides immutable array operations with full TypeScript support. It exposes 15 different methods to easily modify array state including push, pop, unshift, shift, concat, fill, reverse, splice, sort, and more advanced operations like insertItemAtIndex and replaceItemAtIndex.
Examples
Basic array operations
Todo list manager
Advanced array operations
Performance considerations with large arrays
Arguments
Argument value | Type | Description | Default |
---|---|---|---|
initial | T[] | (() => T[]) | Initial array state or a function that returns the initial array | [] |
Returns
Returns an array with two elements:
Return value | Type | Description | Default |
---|---|---|---|
array | T[] | The current array state | [] |
controls | UseArrayStateControls<T> | An object containing all array manipulation methods |
Control Methods
Method | Type | Description |
---|---|---|
push | (...args: T[]) => void | Adds one or more elements to the end of the array |
pop | () => void | Removes the last element from the array |
unshift | (...args: T[]) => void | Adds one or more elements to the beginning of the array |
shift | () => void | Removes the first element from the array |
reverse | () => void | Reverses the order of elements in the array |
concat | (value: T[]) => void | Concatenates the given array to the current array |
fill | (value: T, start?: number, end?: number) => void | Fills array elements with a static value |
clear | () => void | Removes all elements from the array |
setArray | (value: T[]) => void | Replaces the entire array with a new array |
updateItemAtIndex | (index: number, value: T) => void | Updates the element at the specified index |
splice | (...args: Parameters<Array<T>["splice"]>) => void | Changes array contents by removing/replacing existing elements |
removeItemAtIndex | (index: number) => void | Removes the element at the specified index |
replaceItemAtIndex | (index: number, value: T) => void | Replaces the element at the specified index with a new value |
insertItemAtIndex | (index: number, value: T) => void | Inserts a new element at the specified index |
sort | (compareFn?: (a: T, b: T) => number) => void | Sorts the array elements using an optional compare function |
TypeScript Support
The hook is fully typed with TypeScript generics:
Performance Notes
- All operations are immutable and create new array instances
- The hook uses
useCallback
for all control methods to prevent unnecessary re-renders - The return value is memoized with
useMemo
for optimal performance - For large arrays, consider implementing virtualization for rendering
- Use the initializer function pattern for expensive initial computations