...

/

State Toggling in React Using the useToggle Hook

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) => {
const [status, setStatus] = useState(initialStatus)
const toggle = () => {
dispatch(status => !status)
)
return [status, toggle]
}

In the preceding code block, the useToggle custom hook takes an initialStatus as the input argument with false as the default value, and it returns the status and a toggle function. Invoking the toggle function flips the status from false to true, or true to false.

Enhancements to the useToggle hook

The useToggle hook has a very useful function designed with well-defined input arguments and a return value, making it ...