Last active
September 1, 2023 18:03
-
-
Save lalalam123/2276d793ebf06bce019959413f8e82bf to your computer and use it in GitHub Desktop.
Custom Hooks for arrays
This file contains 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 } from 'react'; | |
type ArrayStateActions<T> = { | |
add: (item: T) => void; | |
remove: (item: T) => void; | |
clear: () => void; | |
}; | |
const useArrayState = <T>( | |
inistialItems: T[], | |
): [T[], ArrayStateActions<T>] => { | |
const [items, setItems] = useState(initialItems); | |
const add = (item: T) => setItems([...items, item]); | |
const remove = (item: T) => setItems([...items.filter((i)=> i !== item)]); | |
const clear = () => setItems([]); | |
return [items, {add, remove, clear}]; | |
}; | |
export default useArrayState; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment