VayuUI

useList

A hook to manage an array list with utility functions.

The useList hook provides a convenient way to manage an array state with built-in methods for common operations like adding, removing, updating, and clearing items.

Demo

  • Apple
  • Banana
  • Cherry

Source Code

Copy this code into src/hooks/useList.ts:

import { useState } from 'react';

export const useList = <T,>(initialList: T[] = []) => {
  const [list, setList] = useState<T[]>(initialList);

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

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

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

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

  return { list, add, remove, update, clear };
};

Usage

import { useList } from '@/hooks/useList';

const TodoList = () => {
  const { list, add, remove, clear } = useList(['Buy milk', 'Walk dog']);

  return (
    <div>
      <button onClick={() => add('New Task')}>Add Task</button>
      <button onClick={clear}>Clear All</button>
      <ul>
        {list.map((item, index) => (
          <li key={index}>
            {item} <button onClick={() => remove(index)}>Remove</button>
          </li>
        ))}
      </ul>
    </div>
  );
};

API Reference

Parameters

NameTypeDescription
initialListT[]An optional initial array of items.

Return Value

PropertyTypeDescription
listT[]The current array of items.
add(item: T) => voidAdds an item to the end of the list.
remove(index: number) => voidRemoves an item at the specified index.
update(index: number, newItem: T) => voidUpdates an item at the specified index.
clear() => voidRemoves all items from the list.

On this page