Created
October 19, 2021 07:55
-
-
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`.
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 } 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