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.
import React from 'react';import { useList } from '@abhushanaj/react-hooks';
function App() { const [list, listControls] = useList([1, 2, 3, 4]);
const { firstItem, lastItem, size, clear, reset, set, valueAt, inserAt, updateAt, removeAt } = listControls;
return ( <div> <p>Size: {size}</p> <p>First Item: {firstItem}</p> <p>Last Item: {lastItem}</p> <button onClick={clear}>Clear</button> <button onClick={() => { set([1, 2, 3]); }} > Set [1,2,3] </button>
<button onClick={() => updateAt(0, 4)}>Update Index 0 with 4</button> <button onClick={() => { removeAt(2); }} > Remove index 2 </button> </div> );}
export default App;Properties
- The
insertAt,removeAt,valueAtupdateAtmethods can work both with positive and negative index. Negative index values count back from the last item in the list. - Performing
insertAtwith 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
removeAtandupdateAtwith 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.