Created
December 7, 2020 21:17
-
-
Save laytong/fc65f9e951aecd4358ecc5ab2f7724f3 to your computer and use it in GitHub Desktop.
Handy reusable toggle hook
This file contains 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, useCallback } from 'react'; | |
const useToggle = (initialState) => { | |
const [isOpen, setIsOpen] = useState(initialState); | |
// Flip whatever is the current state | |
const toggle = useCallback( | |
() => setIsOpen(state => !state), | |
[setIsOpen], | |
); | |
// Force isOpen to have a specific value rather than flipping current state | |
const setToggle = useCallback( | |
(value) => setIsOpen(value), | |
[setIsOpen], | |
); | |
return [isOpen, toggle, setToggle]; | |
}; | |
export default useToggle; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment