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
-
Make sure you have
@ridgehkr/useful
installed in your application. If not, you can get started by following the installation instructions. -
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
Property | Required | Type | Description |
---|---|---|---|
initialItems | no | t[] | 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.
Property | Type | Description |
---|---|---|
items | T[] | An array representing the current list of items |
head | T | undefined | The item at the head (index 0) of the List |
tail | T[] | The tail of the List. (All items except for the head ) |
size | number | The number of items currently in the list |
itemAt | (index: number) => T | undefined | Get the value of the List at index index |
prepend | (item: T) => void | Prepend (i.e. add at the beginning) an item to the List |
append | (item: T) => void | Append (i.e. add at the end) an item to the List |
remove | (index: number) => void | Remove the item at index index from the List. |
update | (index: number, newItem: T) => void | Replace an item in the List with item newItem at index index . |