useArray
Useful hook to work with arrays and array methods.
import { useState } from 'react';
export default function useArray(defaultValue) {
const [array, setArray] = useState(defaultValue);
function push(element) {
setArray((a) => [...a, element]);
}
function filter(callback) {
setArray((a) => a.filter(callback));
}
function update(index, newElement) {
setArray((a) => [
...a.slice(0, index),
newElement,
...a.slice(index + 1, a.length - 1),
]);
}
function remove(index) {
setArray((a) => [
...a.slice(0, index),
...a.slice(index + 1, a.length - 1),
]);
}
function clear() {
setArray([]);
}
return { array, set: setArray, push, filter, update, remove, clear };
}
Usage
import useArray from './hooks';
export default function MyComponent() {
const { array, set, push, remove, filter, update, clear } = useArray([]);
return (
// JSX
)
}