⚛
useToggle React Hook
On this page
tsx
import { Dispatch, DispatchWithoutAction } from 'react'import { useCallback, useState } from 'react'/*** @name useToggle* @description Toggle something*/export const useToggle = (initialState = false,): [boolean, DispatchWithoutAction, Dispatch<boolean>] => {// Initialize the stateconst [state, setToggleState] = useState(initialState)// Define and memorize toggler function in case we pass down the comopnent,// This function change the boolean value to it's opposite valueconst toggle = useCallback(() => setToggleState((state) => !state), [])return [state, toggle, setToggleState]}
Usage
ts
const [isToggled, toggle, setToggleState] = useToggle()setToggleState(true)setToggleState(false)toggle()if (isToggled) {// do something}