The Ultimate React Array Management Hook: useArray
A comprehensive React hook that provides helper methods for working with array state, including all common array operations optimized with useCallback for performance.
By Olivier Colonna
Managing array state in React can be cumbersome when you need to perform common operations like adding, removing, updating, or sorting items. The useArray hook provides a powerful solution that encapsulates all these operations with optimized performance.
What is useArray?
The useArray hook is a comprehensive React hook that provides helper methods for working with array state. It includes all the common array operations you'd expect - push, pop, filter, sort, and many more - all optimized with useCallback for performance.
Key Features
🚀 Complete Array Operations
The hook provides methods for:
- Adding items : push , unshift , insert
- Removing items : pop , shift , remove , removeById
- Updating items : update , updateById , replace
- Array manipulation : filter , sort , reverse , clear
- Utility operations : toggle (add/remove based on existence)
⚡ Performance Optimized
All mutation methods are memoized with useCallback , preventing unnecessary re-renders in child components.
🎯 Type Safe
Built with TypeScript generics, providing full type safety for your array elements.
📊 Convenient Properties
Includes helpful properties like isEmpty and length for easy state checking.
Basic Usage
1import { useArray } from "@usehooks-io/hooks";
2
3function BasicExample() {
4 const { array, push, pop, clear } = useArray([1, 2, 3]);
5
6 return (
7 <div>
8 <p>Array: {JSON.stringify(array)}</p>
9 <button onClick={() => push(4)}>Push 4</button>
10 <button onClick={pop}>Pop</button>
11 <button onClick={clear}>Clear</button>
12 </div>
13 );
14}
15
Advanced Operations
ID-Based Operations
The hook provides convenient methods for working with objects that have unique identifiers:
1import { useArray } from "@usehooks-io/hooks";
2
3interface User {
4 id: number;
5 name: string;
6}
7
8function UserList() {
9 const {
10 array: users,
11 removeById,
12 updateById,
13 } = useArray<User>([
14 { id: 1, name: "Alice" },
15 { id: 2, name: "Bob" },
16 ]);
17
18 return (
19 <div>
20 {users.map((user) => (
21 <div key={user.id}>
22 {user.name}
23 <button onClick={() => removeById(user.id)}>Remove</button>
24 <button
25 onClick={() =>
26 updateById(user.id, { name: user.name + " Updated" })
27 }
28 >
29 Update
30 </button>
31 </div>
32 ))}
33 </div>
34 );
35}
36
Array Manipulation
1import { useArray } from "@usehooks-io/hooks";
2
3function ManipulationExample() {
4 const { array, insert, remove, replace } = useArray(["a", "b", "c"]);
5
6 return (
7 <div>
8 <p>Array: {JSON.stringify(array)}</p>
9 <button onClick={() => insert(1, "x")}>Insert 'x' at index 1</button>
10 <button onClick={() => remove(0)}>Remove first item</button>
11 <button onClick={() => replace("b", "y")}>Replace 'b' with 'y'</button>
12 </div>
13 );
14}
15
Toggle Functionality
Perfect for managing selections or favorites:
1import { useArray } from "@usehooks-io/hooks";
2
3function ToggleExample() {
4 const { array: selectedItems, toggle } = useArray<string>(["apple"]);
5 const items = ["apple", "banana", "orange"];
6
7 return (
8 <div>
9 <p>Selected: {JSON.stringify(selectedItems)}</p>
10 {items.map((item) => (
11 <button
12 key={item}
13 onClick={() => toggle(item)}
14 style={{
15 backgroundColor: selectedItems.includes(item)
16 ? "lightblue"
17 : "white",
18 }}
19 >
20 {item}
21 </button>
22 ))}
23 </div>
24 );
25}
26
API Reference
Parameters
- initialArray (optional): The initial array value (defaults to empty array)
Return Value
The hook returns an object with: State
- array : The current array state
- isEmpty : Boolean indicating if array is empty
- length : Current array length Mutation Methods
- set(newArray) : Replace entire array
- push(...items) : Add items to end
- pop() : Remove and return last item
- shift() : Remove and return first item
- unshift(...items) : Add items to beginning
- insert(index, ...items) : Insert items at specific index
- remove(index) : Remove item at index
- removeById(id, key?) : Remove item by ID
- update(index, item) : Update item at index
- updateById(id, updates, key?) : Update item by ID
- clear() : Remove all items
- filter(predicate) : Filter array in place
- sort(compareFn?) : Sort array in place
- reverse() : Reverse array
- replace(oldItem, newItem) : Replace specific item
- toggle(item) : Add/remove item based on existence
Why Use useArray?
1. Reduced Boilerplate
Instead of writing custom state management logic for each array operation, you get them all out of the box.
2. Performance Benefits
All methods are memoized, preventing unnecessary re-renders and improving app performance.
3. Type Safety
Full TypeScript support ensures you catch errors at compile time.
4. Consistent API
All array operations follow a consistent pattern, making your code more predictable and maintainable.
5. Flexibility
Supports both index-based and ID-based operations, covering most real-world use cases.
Real-World Examples
Shopping Cart
1import { useArray } from "@usehooks-io/hooks";
2
3interface Product {
4 id: number;
5 name: string;
6 price: number;
7 quantity: number;
8}
9
10function ShoppingCart() {
11 const {
12 array: cartItems,
13 push,
14 removeById,
15 updateById,
16 clear,
17 } = useArray<Product>([]);
18
19 const addProduct = (product: Omit<Product, "quantity">) => {
20 const existingItem = cartItems.find((item) => item.id === product.id);
21 if (existingItem) {
22 updateById(product.id, { quantity: existingItem.quantity + 1 });
23 } else {
24 push({ ...product, quantity: 1 });
25 }
26 };
27
28 const total = cartItems.reduce(
29 (sum, item) => sum + item.price * item.quantity,
30 0
31 );
32
33 return (
34 <div>
35 <h2>Shopping Cart</h2>
36 {cartItems.map((item) => (
37 <div key={item.id}>
38 {item.name} - Qty: {item.quantity} - ${item.price * item.quantity}
39 <button onClick={() => removeById(item.id)}>Remove</button>
40 </div>
41 ))}
42 <p>Total: ${total.toFixed(2)}</p>
43 <button
44 onClick={() => addProduct({ id: 1, name: "Laptop", price: 1200 })}
45 >
46 Add Laptop
47 </button>
48 <button onClick={clear}>Clear Cart</button>
49 </div>
50 );
51}
52
Conclusion
The useArray hook is a powerful tool that simplifies array state management in React applications. By providing a comprehensive set of optimized methods, it reduces boilerplate code while improving performance and maintainability.
Whether you're building a simple todo list or a complex data management interface, useArray provides the tools you need to handle array operations efficiently and elegantly.
Try it out in your next React project and experience the difference it makes in your development workflow!