Skip to content
Junior–Senior167 views

Creating your own hook for working with an array

Task condition

You need to write a custom hook useArray that provides the ability to add and remove elements from an array. An example of using the hook is shown below.

import { useArray } from "./hooks/useArray";
import "./styles.css";

export default function App() {
  const { value, push, removeByIndex } = useArray<number>([1, 2, 3]);

  return (
    <div>
      <ul>
        {value.map((item, index) => (
          <li key={index}>
            {item}
            <button onClick={() => removeByIndex(index)}>Remove</button>
          </li>
        ))}
      </ul>
      <button onClick={() => push(value.length + 1)}>Add</button>
    </div>
  );
}

Implementation requirements:

  • The hook should accept an initial array value.
  • The returned object should contain the current array (value), a function to add an element to the end (push), and a function to remove an element by index (removeByIndex).
  • When calling push, the array should update by adding the passed value.
  • When calling removeByIndex, the element at the specified index should be removed, and the array should be recalculated without mutating the original state.
  • The hook should use standard React hooks (useState, useCallback, etc.) and work correctly in functional components.
Frontend tasks in the code trainer