useArray
A hook that returns a reactive array with all native Array methods that automatically trigger re-renders.
Installation
import { useArray } from 'data-strcture-react-hooks';
Basic Usage
function MyComponent() {
const array = useArray([1, 2, 3]);
return (
<div>
<p>Length: {array.length}</p>
<button onClick={() => array.push(4)}>Add Item</button>
<button onClick={() => array.pop()}>Remove Last</button>
</div>
);
}
API Reference
Parameters
defaultValue
(T[]): The initial array values
Returns
A reactive array with all native Array methods that automatically trigger re-renders when mutated.
Supported Methods
The returned array supports all native Array methods that mutate the array:
push(...items)
- Adds elements to the endpop()
- Removes and returns the last elementshift()
- Removes and returns the first elementunshift(...items)
- Adds elements to the beginningsplice(start, deleteCount, ...items)
- Changes array contentsreverse()
- Reverses the arraysort(compareFunction?)
- Sorts the arraycopyWithin(target, start, end)
- Copies elements within the arraywith(index, value)
- Returns a new array with a single element changed
Live Example
Try out the useArray hook with this interactive example:
Current Array:
[1, 2, 3, 4, 5]
Length: 5
First element: 1
Last element: 5
Examples
Basic Array Operations
const array = useArray([1, 2, 3]);
// Add elements
array.push(4, 5); // [1, 2, 3, 4, 5]
array.unshift(0); // [0, 1, 2, 3, 4, 5]
// Remove elements
array.pop(); // [0, 1, 2, 3, 4]
array.shift(); // [1, 2, 3, 4]
// Modify elements
array.splice(1, 2, 10, 11); // [1, 10, 11, 4]
array.reverse(); // [4, 11, 10, 1]
array.sort((a, b) => a - b); // [1, 4, 10, 11]
Todo List Example
function TodoList() {
const todos = useArray([]);
const [input, setInput] = useState('');
const addTodo = () => {
if (input.trim()) {
todos.push({ id: Date.now(), text: input, completed: false });
setInput('');
}
};
const toggleTodo = (index: number) => {
todos[index].completed = !todos[index].completed;
};
const removeTodo = (index: number) => {
todos.splice(index, 1);
};
return (
<div>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Add todo..."
/>
<button onClick={addTodo}>Add</button>
{todos.map((todo, index) => (
<div key={todo.id}>
<input
type="checkbox"
checked={todo.completed}
onChange={() => toggleTodo(index)}
/>
<span>{todo.text}</span>
<button onClick={() => removeTodo(index)}>Delete</button>
</div>
))}
</div>
);
}
How It Works
The useArray hook uses JavaScript's Proxy API to intercept method calls on the array. When a mutating method is called, it triggers a re-render of the component by updating an internal state variable. This ensures that your UI stays in sync with the array's state.
TypeScript Support
The hook is fully typed and supports generic types:
const numbers = useArray<number>([1, 2, 3]);
const strings = useArray<string>(['a', 'b', 'c']);
const objects = useArray<{id: number, name: string}>([
{ id: 1, name: 'John' }
]);