Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
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
- Host: GitHub
- URL: https://github.com/ybiquitous/use-toggle
- Owner: ybiquitous
- License: mit
- Created: 2021-04-16T05:17:20.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2024-04-01T20:17:34.000Z (7 months ago)
- Last Synced: 2024-04-14T05:57:18.299Z (7 months ago)
- Topics: hooks, react, utility
- Language: TypeScript
- Homepage: https://npm.im/@ybiquitous/use-toggle
- Size: 2.84 MB
- Stars: 3
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
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]);
```