useList
Manage a list of items
The useList
hook is helpful when you want to manage a list of items.
It provide with helper methods like valueAt
, insertAt
, updateAt
, removeAt
, clear
, reset
, set
and additional properties like firstItem
, lastItem
and size
.
useList
First Item
Last Item
0
1
2
3
Usage
Import the hook from @abhushanaj/react-hooks
and use in required component.
Properties
- The
insertAt
,removeAt
,valueAt
updateAt
methods can work both with positive and negative index. Negative index values count back from the last item in the list. - Performing
insertAt
with positive out of bounds index will result in a sparse array, while negative out of bounds index will simply update the item atindex=0
. - Performing
removeAt
andupdateAt
with out of bounds index will not change the array.
API Reference
Parameters
Parameter | Type | Description | Default |
---|---|---|---|
initialList | Array<T> (optional) | The initial list with items prefilled. | [] |
Return Value
Parameter | Type | Description | Default |
---|---|---|---|
list | Array<T> | The current list. | N/A |
listControls | ListControls | The control options for the list to add, remove etc. | N/A |
Types Reference
1. ListControls
Parameter | Type | Description | Default |
---|---|---|---|
firstItem | T|undefined | The first item of the list. | N/A |
lastItem | T|undefined | The last item of the list. | N/A |
size | number | The size of the list. | N/A |
clear | ()=>void | Clears the list to an empty state. | N/A |
reset | ()=>void | Resets the list to the initial state. | N/A |
set | (newList: Array<T>)=>void | Replaces the existing list with the new list. | N/A |
valueAt | (index:number)=>T | undefined | Gets the item at the given index or returns undefined if does not exists. | N/A |
insertAt | (index:number, value: T)=>void | Inserts the item at the given index and updates the list. | N/A |
updateAt | (index:number, value: T)=>void | Updates the index with the new value and updates the list. | N/A |
removeAt | (index: number)=>void | Removes the item present at index and updates the list. | N/A |
Note: See properties to understand caveats while working with index methods.