This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for React Coding Question on BFE.dev
12. useArray()

Here's one possible implementation of useArray() hook:

import { useState } from "react";

const useArray = (initialValue) => {
  const [array, setArray] = useState(initialValue);

  const push = (element) => {
    setArray((prevArray) => [...prevArray, element]);
  };

  const removeByIndex = (index) => {
    setArray((prevArray) =>
      prevArray.filter((_, i) => i !== index)
    );
  };

  return { value: array, push, removeByIndex };
};

// Usage:
const {value, push, removeByIndex} = useArray([1, 2, 3]);

console.log(value) // [1, 2, 3]

push(4);

console.log(value) // [1, 2, 3, 4]

removeByIndex(1);

console.log(value) // [1, 3, 4]

The useArray() hook returns an object with three properties:

  • value: the current state value (an array)
  • push: a function to add a new element to the array
  • removeByIndex: a function to remove an element from the array by its index

Note: This implementation assumes that the array elements are unique and that the removeByIndex() function should remove only the first element with the given index. If the array can contain duplicate elements, use filter() with a different condition to remove all matching elements.