Skip to main content

useToggle

Use boolean value.

API

function useToggle(initialValue?: boolean): [
value: boolean,
actions: {
toggle: (newValue?: boolean) => void;
toggleOn: () => void;
toggleOff: () => void;
}
];

Params:

  • initialValue: Optional initial value. Default is false.

Results:

  • value: A boolean value that can be changed by the following actions.
  • actions: Actions object.
    • actions.toggle: Toggle the value. If the newValue param is not undefined, the value will be set to the newValue.
    • actions.toggleOn: Set the value to true.
    • actions.toggleOff: Set the value to false.

Example

Value: true
import React from "react";
import { useToggle } from "@lilib/hooks";

function Example() {
const [value, { toggle, toggleOn, toggleOff }] = useToggle(true);

return (
<>
<button onClick={() => toggle()}>Toggle</button>{" "}
<button onClick={toggleOn}>Toggle on</button>{" "}
<button onClick={toggleOff}>Toggle off</button> {`Value: ${value}`}
</>
);
}

export default Example;