Handy syntactic sugar around useState, for toggling a boolean value on and off.
JSXimport { useState, useCallback } from 'react'; export default function useToggle(initialValue = false) { const [value, setValue] = useState(initialValue); const toggle = useCallback(() => { setValue((v) => !v); }, []); return [value, toggle]; }
Last Updated:JSXconst App = () => { const [isOn, toggleIsOn] = useToggle(); return ( <> {isOn ? 'The light is on!' : 'Hey who turned off the lights'} <button onClick={toggleIsOn}>Press me</button> </> ); };