Last active
July 18, 2023 17:09
-
-
Save mayognaise/4e7ff4556bdd004fe247cdd5e8abc4eb to your computer and use it in GitHub Desktop.
A hook to manage boolean
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
/** | |
A hook to manage boolean | |
@example | |
function Example() { | |
const [flag, setFlag] = useBoolean() | |
return ( | |
<> | |
<p>Boolean state: {flag}</p> | |
<button onClick={setFlag.on}>On</button> | |
<button onClick={setFlag.off}>Off</button> | |
<button onClick={setFlag.toggle}>Toggle</button> | |
</> | |
) | |
} | |
*/ | |
import { useMemo, useState } from 'react'; | |
export const useBoolean = (defaultValue = false) => { | |
const [value, setValue] = useState(defaultValue) | |
const callbacks = useMemo( | |
() => ({ | |
on: () => setValue(true), | |
off: () => setValue(false), | |
toggle: () => setValue((prev) => !prev), | |
}), | |
[], | |
) | |
return [value, callbacks] as const | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment