-
-
Notifications
You must be signed in to change notification settings - Fork 340
Expand file tree
/
Copy pathuseToggleArray.ts
More file actions
24 lines (21 loc) · 732 Bytes
/
useToggleArray.ts
File metadata and controls
24 lines (21 loc) · 732 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { useState, useCallback } from 'react'
/**
* Hook for managing an array of items that can be toggled on/off.
* Useful for multi-select checkboxes, capability lists, role assignments, etc.
*
* @example
* const [selectedIds, toggleId, setSelectedIds] = useToggleArray<string>(['a', 'b'])
* toggleId('c') // adds 'c'
* toggleId('a') // removes 'a'
*/
export function useToggleArray<T>(
initialValue: T[] = [],
): [T[], (item: T) => void, (items: T[]) => void] {
const [items, setItems] = useState<T[]>(initialValue)
const toggle = useCallback((item: T) => {
setItems((prev) =>
prev.includes(item) ? prev.filter((i) => i !== item) : [...prev, item],
)
}, [])
return [items, toggle, setItems]
}