JAVASCRIPT
Efficient Array State Management with `useArray`
A custom React hook for managing array state with convenient methods like `add`, `remove`, `update`, and `clear`, simplifying list manipulations.
import { useState, useCallback } from 'react';
export const useArray = (initialArray) => {
const [value, setValue] = useState(initialArray);
const add = useCallback((item) => {
setValue((prev) => [...prev, item]);
}, []);
const removeById = useCallback((id, key = 'id') => {
setValue((prev) => prev.filter((item) => item[key] !== id));
}, []);
const removeIndex = useCallback((index) => {
setValue((prev) => prev.filter((_, i) => i !== index));
}, []);
const updateById = useCallback((id, newItem, key = 'id') => {
setValue((prev) =>
prev.map((item) => (item[key] === id ? { ...item, ...newItem } : item))
);
}, []);
const clear = useCallback(() => setValue([]), []);
const push = useCallback((item) => setValue((prev) => [...prev, item]), []);
const filter = useCallback((callback) => setValue((prev) => prev.filter(callback)), []);
const sort = useCallback((callback) => setValue((prev) => [...prev].sort(callback)), []);
return {
value,
setValue,
add,
removeById,
removeIndex,
updateById,
clear,
push,
filter,
sort,
};
};
How it works: The `useArray` hook simplifies common array manipulations within React components. It provides a stateful array and helper functions like `add`, `removeById`, `updateById`, `clear`, `push`, `filter`, and `sort`. These methods update the array state immutably, triggering re-renders efficiently. It's highly useful for managing lists of items, such as to-do lists, shopping carts, or dynamic forms, centralizing array logic.