Created
February 12, 2021 01:18
-
-
Save caelinsutch/a2f5150095ab5ae847c2257bf9f7414b to your computer and use it in GitHub Desktop.
useToggle
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 } from 'react'; | |
type UseToggle<T> = [T[], (item: any) => void, (items?: T[]) => void]; | |
const useToggle = <T = any>(defaultValues?: T[]): UseToggle<T> => { | |
const [items, setItems] = useState<T[]>(defaultValues || []); | |
const toggleItem = (item: any) => { | |
if (items.includes(item)) { | |
setItems((prev) => prev.filter((i) => i !== item)); | |
} else { | |
setItems((prev) => prev.concat(item)); | |
} | |
}; | |
const reset = (newItems?: T[]) => setItems(newItems || []); | |
return [items, toggleItem, reset]; | |
}; | |
export default useToggle; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment