Last active
February 22, 2026 19:36
-
-
Save Kcko/c9995d2c596be9509af94e621d209dcc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useState, useCallback } from "react" | |
| export function useArray(initialValue) { | |
| const [array, setArray] = useState(initialValue) | |
| const push = useCallback(element => { | |
| setArray(a => [...a, element]) | |
| }, []) | |
| const replace = useCallback((index, newElement) => { | |
| setArray(a => { | |
| return [...a.slice(0, index), newElement, ...a.slice(index + 1)] | |
| }) | |
| }, []) | |
| const filter = useCallback(callback => { | |
| setArray(a => { | |
| return a.filter(callback) | |
| }) | |
| }, []) | |
| const remove = useCallback(index => { | |
| setArray(a => { | |
| return [...a.slice(0, index), ...a.slice(index + 1)] | |
| }) | |
| }, []) | |
| const clear = useCallback(() => { | |
| setArray([]) | |
| }, []) | |
| const reset = useCallback(() => { | |
| setArray(initialValue) | |
| }, [initialValue]) | |
| return { array, set: setArray, push, replace, filter, remove, clear, reset } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment