useToggleuseToggle+useEventRefuseSafeEffectuseEventControluseDebounceuseThrottleuseClickOutsideuseTabsuseDateuseDatesuseImageuseCaptureuseIntersectionObserver
react react-hook ironman30

useToggle

A hook to toggle between true and false.


LINKS

鐵人賽連結


function useToggle(defaultState = false) {
  if (typeof defaultState !== "boolean") {
    throw new Error("UseToggle: defaultState should be Boolean")
  }

  const [state, setState] = useState(defaultState)

  const toggle = useCallback(() => setState(prev => !prev), [])

  return [state, toggle]
}

Params

name type description
defaultStatebooleandefault as false

Return

name type description
stateboolean
togglefunctionto trigger the state

Example

function Example() {
  const [isOpen, toggle] = useToggle()
  return (
    <>
      <Button onClick={toggle}>TOGGLE</Button>
      <Modal isOpen={isOpen} onClose={toggle} isCentered>
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>Hello (´・ω・`)</ModalHeader>
          <ModalCloseButton />

          <ModalFooter>
            <Button colorScheme="blue" mr={3} onClick={toggle}>
              Close
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </>
  )
}