Skip to main content

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 array
    • setArray.unshift: Adds items to the beginning of the array
    • setArray.shift: Removes the first item of the array
    • setArray.pop: Removes the last item of the array
    • setArray.splice: Removes items at a specific position and optionally inserts new items
    • setArray.remove: Removes items at the given indexes
    • setArray.removeAt: Removes the item at the given index
    • setArray.removeBy: Removes items for which the predicate function returns true
    • setArray.updateAt: Updates the item at the given index
    • setArray.updateBy: Updates each item in the array via an iteratee function
    • setArray.insertAt: Inserts an item at the given index
    • setArray.clear: Clears the array
Example
const [array, setArray] = useArrayState<number>([]);

setArray([1, 2, 3]);
setArray.push(4);
setArray.pop();
// ...

Code

🔗 View source 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

NameTypeDescription
initialValueT[] | (() => 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>
);
};

Example