Created
October 26, 2020 22:40
-
-
Save azmenak/6d75a74b40bd46f0368f6beb85b5e7d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useMemo } from "react"; | |
type UseToggleInterface = [ | |
boolean, | |
{ | |
/** | |
* Set state value to `true` | |
*/ | |
on(): void; | |
/** | |
* Set state value to `false` | |
*/ | |
off(): void; | |
/** | |
* Invert the current state value | |
*/ | |
toggle(): void; | |
} | |
]; | |
export function useToggle(defaultValue = false): UseToggleInterface { | |
const [state, setState] = useState(defaultValue); | |
const toggleControl = useMemo( | |
() => ({ | |
on: () => { | |
setState(true); | |
}, | |
off: () => { | |
setState(false); | |
}, | |
toggle: () => { | |
setState((value) => !value); | |
}, | |
}), | |
[] | |
); | |
return [state, toggleControl]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment