To toggle between a boolean flag in React, you can use the below custom hook that uses setState
internally:
import { useState } from 'react'
const useToggle = initialState => {
const [state, setState] = useState(initialState || false);
return [state, () => setState(!state)];
};
Since the function returns an array, with a state and a callback function, you can use it in your component, just like you would for other built-in React hooks, like so:
import React, { useState } from 'react'
import useToggle from 'useToggle'
const toggleComponent = () => {
const [lightsOn, toggleLights] = useToggle();
const [isVisible, toggleSidebar] = useToggle();
return (
<React.Fragment>
<button onClick={toggleLights}>{lightsOn ? '🌞' : '🌒'}</button>;
<button onClick={toggleSidebar}>Toggle sidebar</button>;
<Sidebar visible={isVisible} />
</React.Fragment>
);
};