Snippet
useBool()
edit
This post was formerly called useSwitch
.
I can’t tell you how many times I’ve needed some binary (boolean) state management.
Copy/paste this and change it to suit whatever needs you have.
function useBool(initialState = false) {
const [state, setState] = React.useState(initialState)
const handlers = React.useMemo(
() => ({
on: () => {
setState(true)
},
off: () => {
setState(false)
},
toggle: () => {
setState(s => !s)
},
reset: () => {
setState(initialState)
},
}),
[initialState]
)
return [state, handlers] as const
}
Liked the post?
Give the author a dopamine boost with a few "beard strokes". Click the beard
up to 50 times to show your appreciation.
Kyle Shevlin is the founder & lead software engineer of Agathist, a software development firm with a mission to build good software with good people.