-
Notifications
You must be signed in to change notification settings - Fork 0
/
useToggle.ts
37 lines (30 loc) · 876 Bytes
/
useToggle.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { useCallback, useState } from 'react'
import type { Dispatch, SetStateAction } from 'react'
// --
type ToggleInitial = boolean | (() => boolean)
type ToggleTuple = [boolean, () => void, Dispatch<SetStateAction<boolean>>]
// --
/**
* Returns a tuple containing:
* * A boolean state.
* * A function to toggle that state.
* * A function to set the state manually.
*
* @param i The value state will be set to on first render.
*
* @example
* import { useToggle } from '@locktech/atomic'
*
* export const MyComponent = () => {
* const [open, toggleOpen, setOpen] = useToggle(false)
*
* return ...
* }
*/
const useToggle = (i: ToggleInitial = false): ToggleTuple => {
const [state, setState] = useState(i)
const toggle = useCallback(() => setState(!state), [setState, state])
return [state, toggle, setState]
}
// --
export default useToggle