JAVASCRIPT
Simplify Array State Management with a `useArray` Hook
Develop a `useArray` React hook to streamline operations on an array state, providing convenient functions for adding, removing, updating, and clearing elements.
import { useState, useCallback } from 'react';
function useArray(initialArray) {
const [array, setArray] = useState(initialArray);
const add = useCallback((element) => {
setArray((a) => [...a, element]);
}, []);
const remove = useCallback((index) => {
setArray((a) => a.filter((_, i) => i !== index));
}, []);
const update = useCallback((index, newElement) => {
setArray((a) => a.map((el, i) => (i === index ? newElement : el)));
}, []);
const clear = useCallback(() => {
setArray([]);
}, []);
const reset = useCallback(() => {
setArray(initialArray);
}, [initialArray]);
return { array, set: setArray, add, remove, update, clear, reset };
}
// Example Usage:
/*
function TodoList() {
const { array: todos, add, remove, update, clear, reset } = useArray(['Buy groceries', 'Walk the dog']);
const [newTodo, setNewTodo] = useState('');
return (
<div>
<h2>Todo List</h2>
<input
type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
placeholder="Add new todo"
/>
<button onClick={() => { add(newTodo); setNewTodo(''); }}>Add Todo</button>
<button onClick={clear}>Clear All</button>
<button onClick={reset}>Reset</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => remove(index)}>Remove</button>
<button onClick={() => update(index, todo + ' (updated)')}>Update</button>
</li>
))}
</ul>
</div>
);
}
*/
How it works: The `useArray` hook simplifies common array manipulations within React state. It initializes an array and provides a set of helper functions: `add` to append an element, `remove` to delete by index, `update` to modify an element at a specific index, `clear` to empty the array, and `reset` to revert to the initial array. These functions use `useCallback` to memoize the operations and the functional `setArray` update pattern to ensure correct state updates based on the previous state, preventing common array management pitfalls.