Skip to content

Instantly share code, notes, and snippets.

@mheob
Created October 19, 2021 07:55
Show Gist options
  • Save mheob/e4eff39e634ecc41f276d5b53c2d0819 to your computer and use it in GitHub Desktop.
Save mheob/e4eff39e634ecc41f276d5b53c2d0819 to your computer and use it in GitHub Desktop.
Simple `useToggle` hook which returns the boolean state and the setter methods `on`, `off`, `toggle` and `reset`.
import { useState } from 'react'
export function useToggle(
initialState = false
): [boolean, { on: () => void; off: () => void; toggle: () => void; reset: () => void }] {
const [state, setState] = useState(initialState)
const handlers = {
on: () => {
setState(true)
},
off: () => {
setState(false)
},
toggle: () => {
setState((s) => !s)
},
reset: () => {
setState(initialState)
},
}
return [state, handlers]
}
// ---
//
// Using example
function MyComponent() {
const [isExpanded, { toggle: toggleExpansion }] = useToggle(true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment