Docs
List

List

Manage and manipulate lists

About

The useList hook manages and manipulates lists in a React component. It encapsulates list state and provides convenient methods to modify the list, allowing easy initialization with a default value and offering various methods to add, remove, update, or clear elements within the list.

Parameters

NameTypeDescription
defaultListarrayThe initial list of elements. Default is an empty array.

Return Values

NameParametersDescription
[0]The current list of elements.
[1].setl: arrayReplaces the entire list with a new array l.
[1].pushelement: anyAppends the element to the end of the list.
[1].removeAtindex: numberRemoves the element at the specified index from the list.
[1].insertAtindex: number, element: anyInserts the element at the specified index in the list.
[1].updateAtindex: number, element: anyReplaces the element at the specified index with the element.
[1].clearRemoves all elements from the list.

Installation

Run the following command:

npx scriptkavi-hooks@latest add list

Usage

import { useList } from "@/hooks/list"
import ListDemo from "./ListDemo"
 
export default function App() {
  const [list, { set, push, removeAt, insertAt, updateAt, clear }] = useList([
    "First",
    "Second",
    "Third",
  ])
 
  return (
    <section>
      <header>
        <h1>UseList</h1>
        <button
          disabled={list.length < 1}
          className="link"
          onClick={() => insertAt(1, "woo")}
        >
          Insert After First
        </button>
        <button
          disabled={list.length < 2}
          className="link"
          onClick={() => removeAt(1)}
        >
          Remove Second Item
        </button>
        <button className="link" onClick={() => set([1, 2, 3])}>
          Reset
        </button>
        <button className="link" onClick={() => clear()}>
          Clear
        </button>
      </header>
      <ListDemo
        list={list}
        updateAt={updateAt}
        push={push}
        removeAt={removeAt}
      />
    </section>
  )
}