/

useToggle React Hook

react
On this page
  • Usage
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 state
const [state, setToggleState] = useState(initialState)
// Define and memorize toggler function in case we pass down the component,
// This function change the boolean value to it's opposite value
const toggle = useCallback(() => setToggleState((state) => !state), [])
return [state, toggle, setToggleState]
}

Usage

ts
const [isToggled, toggle, setToggleState] = useToggle()
setToggleState(true)
setToggleState(false)
toggle()
if (setToggle) {
// do something
}
Edit this page
Want to make your own site like this?
Try gatsby-theme-code-notes by Zander Martineau.
Notes on code. My second brain, by Zander Martineau.