We often need to have a boolean state and switch between true & false to show/hide something on a screen We can put such simple logic into a custom hook and make components a bit cleaner
// functions\useBoolean.js
import { useState } from 'react'
export default function useBoolean(initVal = true) {
const [state, setState] = useState(initVal)
const toggleState = () => setState(prevVal => !prevVal)
return [state, toggleState]
}
Usage
import useBoolean from '/functions/useBoolean'
function Component() {
const [state, toggleState] = useBoolean(true)
return (
<>
<div>{state.toString()}</div>
<button onClick={toggleState}>Toggle state</button>
</>
)
}
Similar function can be found in the react-use package under the useToggle hook.