This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for React Coding Question on BFE.dev
7. useToggle()
Here's one way to implement useToggle()
:
import { useState, useCallback } from 'react'
function useToggle(initialState = false): [boolean, () => void] {
const [state, setState] = useState<boolean>(initialState)
const toggle = useCallback(() => {
setState((state) => !state)
}, [])
return [state, toggle]
}
The hook returns an array with two elements: the current on
state and a toggle
function to update it.
Here's how you might use it in App
:
function App() {
const [on, toggle] = useToggle(false)
return (
<div>
<button onClick={toggle}>{on ? 'ON' : 'OFF'}</button>
</div>
)
}
Clicking the button will toggle the on
state, and the button label will update accordingly. Of course, you can use this hook for other types of components, not just buttons.