Skip to content

useToggle

Toogle a boolean value

The useToggle hook is helpful when you want to managing a boolean state and provide a function to toggle it. It is useful when you want to take an opposite action from the current state like hide/show a modal, open/close a navbar etc.

useToggle

Current Value: true

Usage

Import the hook from @abhushanaj/react-hooks and use in required component.

./src/App.tsx
import React from 'react';
import { usePrevious } from '@abhushanaj/react-hooks';
function App() {
const [isOn, toggleOn] = useToggle(true);
return (
<div>
<p>Current Value: {isOn ? 'true' : 'false'}</p>
<button onClick={() => toggleOn()}>{isOn ? 'Toggle to false' : 'Toggle to true'}</button>
<button onClick={() => toggleOn(true)}>Change to true</button>
<button onClick={() => toggleOn(false)}>Change to false</button>
</div>
);
}
export default App;

Properties

  1. The useToggle correctly establishes its initial value, casting it to a boolean if it’s not one (using the Boolean constructor)
  2. Based on the argument passed to the toggle function returned from useToggle it will:
    • Toggle the old state if any non boolean value is passed.
    • Sets the state directly when a true or false is passed.

API Reference

Parameters

ParameterTypeDescriptionDefault
initialValueunknownThe initial value to track and toggle.N/A

Return Value

It returns a tuple with [state, toggleFn] format similar to React’s useState

ParameterTypeDescriptionDefault
statebooleanThe current boolean state.N/A
toggleFn(newValue?: unknown) => voidThe update method to toggle the state.N/A