Install

npm
npm i use-any-hook

Description

The useToggle hook provides an easy way to manage boolean toggle states in your React application. It simplifies managing toggle logic by replacing manual useState togglers with a more reusable and concise API.

Parameters

NameTypeDefaultDescription
initialValuebooleanfalseThe initial value of the toggle state.

Return Values

NameTypeDescription
statebooleanThe current boolean state of the toggle.
togglefunctionA function to toggle the current state (true or false).
setExplicitfunctionA function to explicitly set the state to true or false.

Example

useToggle.example.tsx
import React from "react";
import { useToggle } from "use-any-hook";

function ExampleComponent() {
  const [isOn, toggle, setIsOn] = useToggle();

  return (
    <div>
      <p>State is: {isOn ? "ON" : "OFF"}</p>
      <button onClick={toggle}>Toggle</button>
      <button onClick={() => setIsOn(true)}>Turn ON</button>
      <button onClick={() => setIsOn(false)}>Turn OFF</button>
    </div>
  );
}