https://github.com/alloc/react-ch
Event channels for React
https://github.com/alloc/react-ch
events reactjs
Last synced: 9 months ago
JSON representation
Event channels for React
- Host: GitHub
- URL: https://github.com/alloc/react-ch
- Owner: alloc
- Archived: true
- Created: 2019-12-02T18:32:47.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2023-10-19T23:27:15.000Z (over 2 years ago)
- Last Synced: 2025-04-25T22:37:46.213Z (10 months ago)
- Topics: events, reactjs
- Language: TypeScript
- Homepage:
- Size: 376 KB
- Stars: 27
- Watchers: 2
- Forks: 0
- Open Issues: 7
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# react-ch
The `Channel` class is used to achieve loose coupling between an event source and its subscribers. To notify subscribers, it must be called as a function.
The `useChannel` hook has two different use cases.
- as a shortcut for `useConstant(() => new Channel(name))`
- for subscribing to a channel
```ts
const didLogin = useChannel()
// Listen for "didLogin" events while mounted.
useChannel(didLogin, (user: User) => {...})
// Send an event to subscribers.
didLogin(user)
```
### Async decentralized work
Channels can be used to depend on arbitrary work performed by subscribers. Every event has a promise that resolves with an array of return values (from subscribers).
```ts
// Use a channel to orchestrate animations.
const willAppear = useChannel<[], void>()
await willAppear()
// In a deep descendant:
useChannel(willAppear, () => animate(...))
```