Skip to content

Instantly share code, notes, and snippets.

@mayognaise
Last active July 18, 2023 17:09
Show Gist options
  • Save mayognaise/4e7ff4556bdd004fe247cdd5e8abc4eb to your computer and use it in GitHub Desktop.
Save mayognaise/4e7ff4556bdd004fe247cdd5e8abc4eb to your computer and use it in GitHub Desktop.
A hook to manage boolean
/**
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