-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuse-boolean.ts
54 lines (50 loc) · 1.25 KB
/
use-boolean.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { type Dispatch, type SetStateAction, useCallback, useState } from 'react';
/**
* State returned by the {@link useBoolean} hook.
*/
type BooleanState = {
/**
* Current boolean state value.
*/
readonly value: boolean;
/**
* Set the boolean state to false.
*/
setFalse(): void;
/**
* Set the boolean state to true.
*/
setTrue(): void;
/**
* Set the boolean state to a specific value.
*/
readonly setValue: Dispatch<SetStateAction<boolean>>;
/**
* Switch the state from true to false, or false to true.
*/
toggle(): void;
};
/**
* Use a boolean state value.
*
* All methods returned by this hook are stable, and will not change during
* the lifetime of the component instance.
*
* @param initialValue Set the initial state value (Default: false)
*/
const useBoolean = (initialValue = false): BooleanState => {
const [value, setValue] = useState(initialValue);
const setTrue = useCallback(() => {
setValue(true);
}, []);
const setFalse = useCallback(() => {
setValue(false);
}, []);
const toggle = useCallback(() => {
setValue((current) => {
return !current;
});
}, []);
return { setFalse, setTrue, setValue, toggle, value };
};
export { type BooleanState, useBoolean };