useArrayState
A custom hook for conveniently managing array state while maintaining immutability.
setArray: A function that updates the array state, bundled with array mutation methods.setArray.push: Adds items to the end of the arraysetArray.unshift: Adds items to the beginning of the arraysetArray.shift: Removes the first item of the arraysetArray.pop: Removes the last item of the arraysetArray.splice: Removes items at a specific position and optionally inserts new itemssetArray.remove: Removes items at the given indexessetArray.removeAt: Removes the item at the given indexsetArray.removeBy: Removes items for which the predicate function returnstruesetArray.updateAt: Updates the item at the given indexsetArray.updateBy: Updates each item in the array via an iteratee functionsetArray.insertAt: Inserts an item at the given indexsetArray.clear: Clears the array
Example
const [array, setArray] = useArrayState<number>([]);
setArray([1, 2, 3]);
setArray.push(4);
setArray.pop();
// ...
Code
Interface
typescript
interface ArrayStateSetters<T> extends Dispatch<SetStateAction<T[]>> {
push: (...items: T[]) => void;
unshift: (...items: T[]) => void;
shift: () => void;
pop: () => void;
splice: (start: number, deleteCount: number, ...items: T[]) => void;
remove: (...indexes: number[]) => void;
removeAt: (index: number) => void;
removeBy: (predicate: (item: T, index: number) => boolean) => void;
updateAt: (index: number, item: T) => void;
updateBy: (iteratee: (item: T, index: number) => T) => void;
insertAt: (index: number, item: T) => void;
clear: () => void;
}
typescript
function useArrayState<T>(initialValue: T[]): [T[], ArrayStateSetters<T>]
Parameters
| Name | Type | Description |
|---|---|---|
initialValue | T[] | (() => T[]) | The initial array value or a function that returns the initial value |
Usage
typescript
import { useArrayState } from '@modern-kit/react'
const Example = () => {
const [array, setArray] = useArrayState<number>([]);
const addItem = () => {
setArray.push(Math.floor(Math.random() * 100));
};
return (
<div>
<button onClick={addItem}>Add random number</button>
<button onClick={() => setArray.clear()}>Clear all</button>
<button onClick={() => setArray([1, 2, 3])}>Set array directly</button>
<ul>
{array.map((item, index) => (
<li key={index}>
{item} <button onClick={() => setArray.removeAt(index)}>Remove</button>
</li>
))}
</ul>
</div>
);
};