useHooks.iov4.1.2
DocsBlogGitHub
Hooks
No hooks found in any category.

useArray

state

Installation

npx usehooks-cli@latest add use-array

Description

A powerful React hook that provides helper methods for working with array state, including push, pop, filter, sort, and other common array operations with optimized performance using useCallback.

Parameters

NameTypeDefaultDescription
initialArray?T[][]The initial array value to start with

Return Type

UseArrayReturn<T>
PropertyTypeDescription
arrayT[]The current array state
set(newArray: T[]) => voidReplace the entire array with a new array
push(...items: T[]) => voidAdd one or more items to the end of the array
pop() => T | undefinedRemove and return the last item from the array
shift() => T | undefinedRemove and return the first item from the array
unshift(...items: T[]) => voidAdd one or more items to the beginning of the array
insert(index: number, ...items: T[]) => voidInsert one or more items at a specific index
remove(index: number) => voidRemove an item at a specific index
removeById(id: any, key?: keyof T) => voidRemove an item by its ID or specified key
update(index: number, item: T) => voidUpdate an item at a specific index
updateById(id: any, updates: Partial<T>, key?: keyof T) => voidUpdate an item by its ID or specified key with partial updates
clear() => voidRemove all items from the array
filter(predicate: (item: T, index: number) => boolean) => voidFilter the array in place using a predicate function
sort(compareFn?: (a: T, b: T) => number) => voidSort the array in place

Examples

Basic Array Operations

Managing a list of items with common operations

1const { array, push, pop, remove, clear } = useArray([1, 2, 3]); 2 3return ( 4 <div> 5 <p>Array: {JSON.stringify(array)}</p> 6 <button onClick={() => push(array.length + 1)}>Add Item</button> 7 <button onClick={pop}>Remove Last</button> 8 <button onClick={() => remove(0)}>Remove First</button> 9 <button onClick={clear}>Clear All</button> 10 </div> 11);

Dependencies

react

Notes

  • All mutation methods are memoized with useCallback for performance
  • Supports generic types for type-safe array operations
  • Provides both index-based and ID-based operations
  • Maintains referential equality for unchanged arrays

Implementation

1"use client"; 2 3import { useState, useCallback } from "react"; 4 5interface UseArrayReturn<T> { 6 array: T[]; 7 set: (newArray: T[]) => void; 8 push: (...items: T[]) => void; 9 pop: () => T | undefined; 10 shift: () => T | undefined; 11 unshift: (...items: T[]) => void; 12 insert: (index: number, ...items: T[]) => void; 13 remove: (index: number) => void; 14 removeById: (id: any, key?: keyof T) => void; 15 update: (index: number, item: T) => void; 16 updateById: (id: any, item: Partial<T>, key?: keyof T) => void; 17 clear: () => void; 18 filter: (predicate: (item: T, index: number) => boolean) => void; 19 sort: (compareFn?: (a: T, b: T) => number) => void; 20 reverse: () => void; 21 replace: (oldItem: T, newItem: T) => void; 22 toggle: (item: T) => void; 23 isEmpty: boolean; 24 length: number; 25} 26 27export function useArray<T>(initialArray: T[] = []): UseArrayReturn<T> { 28 const [array, setArray] = useState<T[]>(initialArray); 29 30 const set = useCallback((newArray: T[]) => { 31 setArray(newArray); 32 }, []); 33 34 const push = useCallback((...items: T[]) => { 35 setArray((prev) => [...prev, ...items]); 36 }, []); 37 38 const pop = useCallback((): T | undefined => { 39 let poppedItem: T | undefined; 40 setArray((prev) => { 41 if (prev.length === 0) return prev; 42 poppedItem = prev[prev.length - 1]; 43 return prev.slice(0, -1); 44 }); 45 return poppedItem; 46 }, []); 47 48 const shift = useCallback((): T | undefined => { 49 let shiftedItem: T | undefined; 50 setArray((prev) => { 51 if (prev.length === 0) return prev; 52 shiftedItem = prev[0]; 53 return prev.slice(1); 54 }); 55 return shiftedItem; 56 }, []); 57 58 const unshift = useCallback((...items: T[]) => { 59 setArray((prev) => [...items, ...prev]); 60 }, []); 61 62 const insert = useCallback((index: number, ...items: T[]) => { 63 setArray((prev) => { 64 const newArray = [...prev]; 65 newArray.splice(index, 0, ...items); 66 return newArray; 67 }); 68 }, []); 69 70 const remove = useCallback((index: number) => { 71 setArray((prev) => { 72 if (index < 0 || index >= prev.length) return prev; 73 return prev.filter((_, i) => i !== index); 74 }); 75 }, []); 76 77 const removeById = useCallback((id: any, key: keyof T = "id" as keyof T) => { 78 setArray((prev) => prev.filter((item) => item[key] !== id)); 79 }, []); 80 81 const update = useCallback((index: number, item: T) => { 82 setArray((prev) => { 83 if (index < 0 || index >= prev.length) return prev; 84 const newArray = [...prev]; 85 newArray[index] = item; 86 return newArray; 87 }); 88 }, []); 89 90 const updateById = useCallback( 91 (id: any, updates: Partial<T>, key: keyof T = "id" as keyof T) => { 92 setArray((prev) => 93 prev.map((item) => (item[key] === id ? { ...item, ...updates } : item)) 94 ); 95 }, 96 [] 97 ); 98 99 const clear = useCallback(() => { 100 setArray([]); 101 }, []); 102 103 const filter = useCallback( 104 (predicate: (item: T, index: number) => boolean) => { 105 setArray((prev) => prev.filter(predicate)); 106 }, 107 [] 108 ); 109 110 const sort = useCallback((compareFn?: (a: T, b: T) => number) => { 111 setArray((prev) => [...prev].sort(compareFn)); 112 }, []); 113 114 const reverse = useCallback(() => { 115 setArray((prev) => [...prev].reverse()); 116 }, []); 117 118 const replace = useCallback((oldItem: T, newItem: T) => { 119 setArray((prev) => { 120 const index = prev.indexOf(oldItem); 121 if (index === -1) return prev; 122 const newArray = [...prev]; 123 newArray[index] = newItem; 124 return newArray; 125 }); 126 }, []); 127 128 const toggle = useCallback((item: T) => { 129 setArray((prev) => { 130 const index = prev.indexOf(item); 131 if (index === -1) { 132 return [...prev, item]; 133 } else { 134 return prev.filter((_, i) => i !== index); 135 } 136 }); 137 }, []); 138 139 return { 140 array, 141 set, 142 push, 143 pop, 144 shift, 145 unshift, 146 insert, 147 remove, 148 removeById, 149 update, 150 updateById, 151 clear, 152 filter, 153 sort, 154 reverse, 155 replace, 156 toggle, 157 isEmpty: array.length === 0, 158 length: array.length, 159 }; 160} 161 162export default useArray; 163