Skip to content

Instantly share code, notes, and snippets.

@laytong
Created December 7, 2020 21:17
Show Gist options
  • Save laytong/fc65f9e951aecd4358ecc5ab2f7724f3 to your computer and use it in GitHub Desktop.
Save laytong/fc65f9e951aecd4358ecc5ab2f7724f3 to your computer and use it in GitHub Desktop.
Handy reusable toggle hook
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