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

Returns

The hook returns an object with the following properties: