JAVASCRIPT

useArray Hook for Managing Array State

Implement a `useArray` React hook providing common utility functions (add, remove, update, clear) for managing array state in a declarative way.

import { useState } from 'react';

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

  const add = (item) => {
    setArray((prev) => [...prev, item]);
  };

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

  const update = (index, newItem) => {
    setArray((prev) =>
      prev.map((item, i) => (i === index ? newItem : item))
    );
  };

  const clear = () => {
    setArray([]);
  };

  const filter = (callback) => {
    setArray((prev) => prev.filter(callback));
  };
  
  const reset = () => {
    setArray(initialArray);
  }

  return { array, setArray, add, remove, update, clear, filter, reset };
};

// Example Usage:
// import React, { useState } from 'react';
// function TodoList() {
//   const { array: todos, add, remove, update, clear, reset } = useArray(['Learn React', 'Build a Hook', 'Deploy App']);
//   const [newTodo, setNewTodo] = useState('');
//
//   const handleAddTodo = () => {
//     if (newTodo.trim()) {
//       add(newTodo);
//       setNewTodo('');
//     }
//   };
//
//   return (
//     <div>
//       <input
//         type="text"
//         value={newTodo}
//         onChange={(e) => setNewTodo(e.target.value)}
//         placeholder="Add new todo"
//       />
//       <button onClick={handleAddTodo}>Add</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 + ' (Done)')}>Mark Done</button>
//           </li>
//         ))}
//       </ul>
//     </div>
//   );
// }
How it works: The `useArray` hook provides a convenient way to manage an array in React state, abstracting common array manipulation operations. It initializes the array state and returns the current `array` along with functions like `add`, `remove`, `update`, `clear`, `filter`, and `reset`. These functions use functional state updates (`setArray(prev => ...)`) to ensure correct state transitions, making array management within components more declarative and less error-prone.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs