API Reference
useList

useList

useList is a hook that provides a way to manage a List of items within your React components. See the API Reference for more details. You can learn more about how lists work on Wikipedia (opens in a new tab) or the NIST (opens in a new tab).

Usage

  1. Make sure you have @ridgehkr/useful installed in your application. If not, you can get started by following the installation instructions.

  2. Import useList into your component.

import { useList } from '@ridgehkr/useful'

Example: Managing a List of Strings

MyListComponent.tsx
import { useList, List } from '@ridgehkr/useful'
 
function MyListComponent() {
  // Initialize the list with some items
  const { items, head, size, prepend, remove, append }: List = useList<string>([
    'Item 1',
    'Item 2',
    'Item 3',
  ])
 
  const addItem = (item: string) => {
    prepend(item)
  }
 
  const removeItem = (index: number) => {
    remove(index)
  }
 
  const addToEnd = (item: string) => {
    append(item)
  }
 
  return (
    <div>
      <ul>
        {items.map((item, index) => (
          <li key={index}>
            {item}
            <button onClick={() => removeItem(index)}>Remove Item</button>
          </li>
        ))}
      </ul>
      <button onClick={() => addItem('New First Item')}>Prepend Item</button>
      <button onClick={() => addToEnd('New Item at the End')}>
        Append Item
      </button>
 
      <p>List size: {size()}</p>
      <p>First item (head): {head}</p>
    </div>
  )
}

API Reference

Hook Signature

useList<T>(initialItems?: T[]): List<T>

Parameters

PropertyRequiredTypeDescription
initialItemsnot[]Items with which to initially populate the List

Return Value

The useList hook returns a List object containing the properties of the List along with several functions for interacting with it.

PropertyTypeDescription
itemsT[]An array representing the current list of items
headT | undefinedThe item at the head (index 0) of the List
tailT[]The tail of the List. (All items except for the head)
sizenumberThe number of items currently in the list
itemAt(index: number) => T | undefinedGet the value of the List at index index
prepend(item: T) => voidPrepend (i.e. add at the beginning) an item to the List
append(item: T) => voidAppend (i.e. add at the end) an item to the List
remove(index: number) => voidRemove the item at index index from the List.
update(index: number, newItem: T) => voidReplace an item in the List with item newItem at index index.