Skip to content

Instantly share code, notes, and snippets.

@caelinsutch
Created February 12, 2021 01:18
Show Gist options
  • Save caelinsutch/a2f5150095ab5ae847c2257bf9f7414b to your computer and use it in GitHub Desktop.
Save caelinsutch/a2f5150095ab5ae847c2257bf9f7414b to your computer and use it in GitHub Desktop.
useToggle
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