← Back to all snippets
JAVASCRIPT

Custom `useList` Hook for Array State Management

Create a powerful custom `useList` hook in React to efficiently manage arrays of items, enabling add, remove, and update operations with ease.

import React, { useState } from 'react';

function useList(initialList = []) {
  const [list, setList] = useState(initialList);

  const add = (item) => {
    setList((prevList) => [...prevList, item]);
  };

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

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

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

  const filter = (predicate) => {
    setList((prevList) => prevList.filter(predicate));
  };

  return {
    list,
    add,
    remove,
    update,
    clear,
    filter,
    setList, // Optionally expose setList directly for full control
  };
}

// Example Usage:
// function MyShoppingList() {
//   const { list, add, remove, update, clear } = useList(['Apples', 'Milk']);

//   const handleAddItem = () => {
//     const newItem = prompt('Enter a new item:');
//     if (newItem) add(newItem);
//   };

//   return (
//     <div>
//       <h2>Shopping List</h2>
//       <ul>
//         {list.map((item, index) => (
//           <li key={index}>
//             {item}
//             <button onClick={() => remove(index)}>Remove</button>
//             <button onClick={() => update(index, prompt('Update item:', item))}>Update</button>
//           </li>
//         ))}
//       </ul>
//       <button onClick={handleAddItem}>Add Item</button>
//       <button onClick={clear}>Clear List</button>
//     </div>
//   );
// }
How it works: The `useList` custom hook simplifies common array manipulations within React components. It manages an array state using `useState` and provides helper functions like `add`, `remove`, `update`, `clear`, and `filter` to perform common operations on the list. This centralizes array logic, ensuring immutability and making components cleaner and easier to reason about when dealing with dynamic lists of items.

Need help integrating this into your project?

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

Hire DigitalCodeLabs