useToggle
The useToggle
Hook allows you to easily toggle a boolean state value between true
and false
.
Here's an example:
import { useState, useCallback } from 'react'
function useToggle(initialState = false) {
const [state, setState] = useState(initialState)
const toggle = useCallback(() => {
setState((prevState) => !prevState)
}, [])
return [state, toggle]
}
function MyComponent() {
const [isOn, toggleIsOn] = useToggle(false)
return (
<div>
<p>Is the light on? {isOn ? 'Yes' : 'No'}</p>
<button onClick={toggleIsOn}>Toggle</button>
</div>
)
}
In this example, we define a useToggle
Hook that takes an optional initialState
boolean value and returns a tuple with the current state value and a toggle
function to toggle the state value between true
and false
. We use the useState
and useCallback
Hooks to manage the state and create a memoized toggle function. Inside our component, we use the useToggle
Hook to create an isOn
state variable and a toggleIsOn
function that we can use to toggle the value of isOn
. We render the current value of isOn
and a button that calls the toggleIsOn
function when clicked.