State Toggling in React Using the useToggle Hook
Learn about the useToggle custom hook, which implements the functionality of toggling boolean states.
Refactoring useToggle
hook
In the internal implementation of the useToggle
custom hook, the React useState
hook is utilized.
Taking one example, we have had this idea of switching a state between true
and false
for a while. We use it in switchable cases, such as toggling a checkbox, hovering over a text, raising an error, or anything that simulates a light switch. Let's see the image below for one of the usages:
Can we abstract this idea to provide such a boolean state as well as the toggle functionality? Let's start refactoring:
const useToggle = (initialStatus = false) => {// The setter function is named 'setStatus' hereconst [status, setStatus] = useState(initialStatus);const toggle = () => {// We must use 'setStatus' to update the statesetStatus(prevStatus => !prevStatus);};return [status, toggle];};
In the code above, the useToggle
custom hook accepts an optional initialStatus
argument, which defaults to false
if no value is provided. It uses React’s useState
hook to create a status
variable along with its corresponding updater function, setStatus
. The hook also defines a toggle
function that flips the value of status
by updating it to the opposite of its previous value. Finally, the hook returns both the current status
and the toggle
function, allowing components to easily manage and switch a boolean state.