- Published on
- -2 mins read
useArray Hook - modifying lists
- Authors
- Name
- Seraj Vahdati
- @seraj
implementation
useArray.js
import { useState } from "react"
const useArray = (defaultValue) => { const [array, setArray] = useState(defaultValue)
const push = (element) => setArray(a => [...a, element]);
const filter = (callback) => setArray(a => a.filter(callback));
const update = (index, newElement) => { setArray(a => [ ...a.slice(0, index), newElement, ...a.slice(index + 1, a.length), ]) }
const remove = (index) => { setArray(a => [...a.slice(0, index), ...a.slice(index + 1, a.length)]) }
const clear = () => setArray([]);
return {array, set: setArray, push, filter, update, remove, clear }}
export default useArray;
usage:
Array.js
import useArray from "./useArray"
export default function ArrayComponent() { const { array, set, push, remove, filter, update, clear } = useArray([1, 2, 3, 4, 5, 6])
return ( <div> <div>{array.join(", ")}</div> <button onClick={() => push(7)}>Add 7</button> <button onClick={() => update(1, 9)}>Change Second Element To 9</button> <button onClick={() => remove(1)}>Remove Second Element</button> <button onClick={() => filter(n => n < 3)}> Keep Numbers Less Than 4 </button> <button onClick={() => set([1, 2])}>Set To 1, 2</button> <button onClick={clear}>Clear</button> </div> )}