useArray Hook
A custom React Hook for array state management with common operations (TypeScript)
Code
import { useState, useCallback } from 'react';
function useArray<T>(initialValue: T[] = []): {
array: T[];
setArray: React.Dispatch<React.SetStateAction<T[]>>;
push: (item: T) => void;
pop: () => void;
shift: () => void;
unshift: (item: T) => void;
splice: (index: number, deleteCount: number, ...items: T[]) => void;
filter: (callback: (item: T, index: number, array: T[]) => boolean) => void;
map: (callback: (item: T, index: number, array: T[]) => T) => void;
clear: () => void;
removeById: (idKey: keyof T, id: T[keyof T]) => void;
} {
const [array, setArray] = useState<T[]>(initialValue);
const push = useCallback((item: T) => {
setArray(prev => [...prev, item]);
}, []);
const pop = useCallback(() => {
setArray(prev => prev.slice(0, -1));
}, []);
const shift = useCallback(() => {
setArray(prev => prev.slice(1));
}, []);
const unshift = useCallback((item: T) => {
setArray(prev => [item, ...prev]);
}, []);
const splice = useCallback((index: number, deleteCount: number, ...items: T[]) => {
setArray(prev => {
const newArray = [...prev];
newArray.splice(index, deleteCount, ...items);
return newArray;
});
}, []);
const filter = useCallback((callback: (item: T, index: number, array: T[]) => boolean) => {
setArray(prev => prev.filter(callback));
}, []);
const map = useCallback((callback: (item: T, index: number, array: T[]) => T) => {
setArray(prev => prev.map(callback));
}, []);
const clear = useCallback(() => {
setArray([]);
}, []);
const removeById = useCallback((idKey: keyof T, id: T[keyof T]) => {
setArray(prev => prev.filter(item => item[idKey] !== id));
}, []);
return {
array,
setArray,
push,
pop,
shift,
unshift,
splice,
filter,
map,
clear,
removeById,
};
}
// Usage example
// const { array: todos, push, removeById, clear } = useArray([
// { id: 1, text: 'Learn React' },
// { id: 2, text: 'Build Hooks' }
// ]);
// push({ id: 3, text: 'Use useArray' });
// removeById('id', 2);
// clear();