Socket
Book a DemoInstallSign in
Socket

@ybiquitous/use-toggle

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ybiquitous/use-toggle

React useToggle() hook

latest
Source
npmnpm
Version
0.1.2
Version published
Maintainers
1
Created
Source

useToggle()

npm

React useToggle() hook, which makes it easy to handle a togglable (boolean) state.

  • React 16.8+
  • No dependencies
  • TypeScript support

Install

npm install @ybiquitous/use-toggle

Usage

import useToggle from "@ybiquitous/use-toggle";

function Check() {
  const [checked, check, uncheck, toggle] = useToggle();

  return (
    <p>
      <input type="checkbox" checked={checked} onChange={toggle} />
      <button onClick={check}>Check</button>
      <button onClick={uncheck}>Uncheck</button>
    </p>
  );
}

function Show() {
  const [isShown, show, hide] = useToggle();

  return (
    <p>
      <button onClick={show}>Show</button>
      <button onClick={hide}>Hide</button>
      {isShown && <strong>Hello</strong>}
    </p>
  );
}

See also the online demo!

Why not useState()

This utility hook aims to reduce the following boilerplate with useState():

function App() {
  const [isShown, setShown] = useState(false);
  const toggle = setShown((state) => !state);
  const show = () => setShown(true);
  const hide = () => setShown(false);

  const showButton = <button onClick={show}>Show</button>;
  const hideButton = <button onClick={hide}>Hide</button>;

  // ...
}

In addition, this package benefits performance by useCallback(). This means that it is equivalent to:

const show = useCallback(() => setShown(true), [setShown]);

Keywords

react

FAQs

Package last updated on 01 Jan 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts