Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/ybiquitous/use-toggle

React useToggle() hook
https://github.com/ybiquitous/use-toggle

hooks react utility

Last synced: about 8 hours ago
JSON representation

React useToggle() hook

Awesome Lists containing this project

README

        

# useToggle()

[![npm](https://img.shields.io/npm/v/@ybiquitous/use-toggle.svg)](https://www.npmjs.com/package/@ybiquitous/use-toggle)

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

- React 16.8+
- No dependencies
- TypeScript support

## Install

```shell
npm install @ybiquitous/use-toggle
```

## Usage

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

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

return (



Check
Uncheck


);
}

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

return (


Show
Hide
{isShown && Hello}


);
}
```

See also the [online demo](https://codesandbox.io/s/vigorous-frost-199yl)!

## Why not useState()

This utility hook aims to reduce the following boilerplate with [`useState()`](https://reactjs.org/docs/hooks-reference.html#usestate):

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

const showButton = Show;
const hideButton = Hide;

// ...
}
```

In addition, this package benefits performance by [`useCallback()`](https://reactjs.org/docs/hooks-reference.html#usecallback).
This means that it is equivalent to:

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