diff options
| author | Armand Philippot <git@armandphilippot.com> | 2023-10-30 11:18:11 +0100 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2023-11-11 18:15:27 +0100 |
| commit | 84a679b0e48ed76eee2fa44d3caac83591aa3c8c (patch) | |
| tree | 1d418a6c514ff8a04b84ba35c98736e8450f968c /src/utils/hooks/use-boolean/use-boolean.ts | |
| parent | 60c49f18389ff625177a57277ef8f292a31097bf (diff) | |
feat(hooks): add useBoolean and useToggle hooks
Diffstat (limited to 'src/utils/hooks/use-boolean/use-boolean.ts')
| -rw-r--r-- | src/utils/hooks/use-boolean/use-boolean.ts | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/src/utils/hooks/use-boolean/use-boolean.ts b/src/utils/hooks/use-boolean/use-boolean.ts new file mode 100644 index 0000000..35cb00c --- /dev/null +++ b/src/utils/hooks/use-boolean/use-boolean.ts @@ -0,0 +1,44 @@ +import { useCallback, useState } from 'react'; + +export type UseBooleanReturn = { + /** + * Set state as true. + */ + activate: () => void; + /** + * Set state as false. + */ + deactivate: () => void; + /** + * Current state. + */ + state: boolean; + /** + * Switch state. + */ + toggle: () => void; +}; + +/** + * React hook to deal with boolean states. + * + * @param {boolean} [initialState] - The initial state. + * @returns {UseBooleanReturn} The state and utility functions to update it. + */ +export const useBoolean = (initialState = false): UseBooleanReturn => { + const [state, setState] = useState(initialState); + + const activate = useCallback(() => { + setState(true); + }, []); + + const deactivate = useCallback(() => { + setState(false); + }, []); + + const toggle = useCallback(() => { + setState((prevState) => !prevState); + }, []); + + return { activate, deactivate, state, toggle }; +}; |
