← Back to all snippets
JAVASCRIPT

Managing Dynamic Lists with useList Custom Hook

Develop a `useList` React hook to easily manage array state with utility functions like add, remove, and update, simplifying dynamic list operations.

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

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

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

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

  const clear = React.useCallback(() => {
    setList([]);
  }, []);

  const reset = React.useCallback(() => {
    setList(initialList);
  }, [initialList]);

  return {
    list,
    setList, // Allow direct state manipulation if needed
    add,
    remove,
    update,
    clear,
    reset,
  };
}

// Example usage:
function TodoList() {
  const todos = useList(['Buy groceries', 'Walk the dog']);
  const [newItem, setNewItem] = React.useState('');

  const handleAddTodo = () => {
    if (newItem.trim()) {
      todos.add(newItem);
      setNewItem('');
    }
  };

  return (
    React.createElement("div", null,
      React.createElement("h2", null, "My Todos"),
      React.createElement("ul", null,
        todos.list.map((todo, index) => (
          React.createElement("li", { key: index },
            todo,
            React.createElement("button", { onClick: () => todos.remove(index) }, "x"),
            React.createElement("button", { onClick: () => todos.update(index, 'Updated: ' + todo) }, "Edit")
          )
        ))
      ),
      React.createElement("input", {
        type: "text",
        value: newItem,
        onChange: (e) => setNewItem(e.target.value),
        placeholder: "Add new todo"
      }),
      React.createElement("button", { onClick: handleAddTodo }, "Add Todo"),
      React.createElement("button", { onClick: todos.clear }, "Clear All"),
      React.createElement("button", { onClick: todos.reset }, "Reset Todos")
    )
  );
}
How it works: The `useList` hook provides a convenient way to manage array-based state in React components, offering a set of common utility functions like `add`, `remove`, `update`, `clear`, and `reset`. It encapsulates the `useState` logic for arrays, making component code cleaner and more focused on business logic. By returning an object with both the current `list` and these helper methods (memoized with `useCallback` for stability), it streamlines operations on dynamic lists, common in forms, todo applications, or any UI requiring editable collections 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