useArray

Author
AI Engineer
Languages

Implement a useArray hook that manages an array of items with additional utility methods.

It is more convenient to use useArray over plain useState because in the latter case, you would always have to create a new array, mutate it, then set state to use the new array, which can be quite cumbersome.

The hook should work generically with arrays of any types.

const defaultValue = ['apple', 'banana'];
export default function Component() {
const { array, push, update, remove, filter, set, clear } = useArray();
return (
<div>
<p>Fruits: {array.join(', ')}</p>
<button onClick={() => push('orange')}>Add orange</button>
<button onClick={() => update(1, 'grape')}>
Change second item to grape
</button>
<button onClick={() => remove(0)}>Remove first</button>
<button onClick={() => filter((fruit) => fruit.includes('a'))}>
Keep fruits containing 'a'
</button>
<button onClick={() => set(defaultValue)}>Reset</button>
<button onClick={clear}>Clear list</button>
</div>
);
}

Arguments

  • defaultValue: The initial array of items

Returns

The hook returns an object with the following properties:

  • array: The current array of items
  • set: (newArray) => void: A function that sets the array of items. This must be the same type as the setter function of useState
  • push: (item) => void: A function that adds an item to the end of the array
  • remove: (index: number) => void: A function that removes an item from the array by index
  • filter: (predicate) => void: A function that filters the array based on a predicate function. predicate must be the same type as the argument of Array.prototype.filter
  • update: (index: number, newItem) => void: A function that replaces an item in the array at index
  • clear: () => void: A function that clears the array