Skip to content

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
Size: 4Try adding and removing items on the list.

Usage

Import the hook from @abhushanaj/react-hooks and use in required component.

./src/App.tsx
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

  1. 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.
  2. 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 at index=0.
  3. Performing removeAt and updateAt with out of bounds index will not change the array.

API Reference

Parameters

ParameterTypeDescriptionDefault
initialListArray<T> (optional)The initial list with items prefilled.[]

Return Value

ParameterTypeDescriptionDefault
listArray<T>The current list.N/A
listControlsListControlsThe control options for the list to add, remove etc.N/A

Types Reference

1. ListControls

ParameterTypeDescriptionDefault
firstItemT|undefinedThe first item of the list.N/A
lastItemT|undefinedThe last item of the list.N/A
sizenumberThe size of the list.N/A
clear()=>voidClears the list to an empty state.N/A
reset()=>voidResets the list to the initial state.N/A
set(newList: Array<T>)=>voidReplaces the existing list with the new list.N/A
valueAt(index:number)=>T | undefinedGets the item at the given index or returns undefined if does not exists.N/A
insertAt(index:number, value: T)=>voidInserts the item at the given index and updates the list.N/A
updateAt(index:number, value: T)=>voidUpdates the index with the new value and updates the list.N/A
removeAt(index: number)=>voidRemoves the item present at index and updates the list.N/A

Note: See properties to understand caveats while working with index methods.