Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/susisu/react-use-source-sink
Creates a pair of source and sink
https://github.com/susisu/react-use-source-sink
Last synced: 10 days ago
JSON representation
Creates a pair of source and sink
- Host: GitHub
- URL: https://github.com/susisu/react-use-source-sink
- Owner: susisu
- License: mit
- Created: 2019-11-23T11:45:49.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2024-06-18T22:51:59.000Z (5 months ago)
- Last Synced: 2024-10-11T21:19:36.789Z (27 days ago)
- Language: JavaScript
- Homepage:
- Size: 479 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# @susisu/react-use-source-sink
[![CI](https://github.com/susisu/react-use-source-sink/workflows/CI/badge.svg)](https://github.com/susisu/react-use-source-sink/actions?query=workflow%3ACI)
``` shell
# npm
npm i @susisu/react-use-source-sink
# yarn
yarn add @susisu/react-use-source-sink
# pnpm
pnpm add @susisu/react-use-source-sink
```## Usage
``` tsx
import React, { useEffect } from "react";
import { useSourceSink } from "@susisu/react-use-source-sink";const Hello: React.FC = () => {
const [source, sink] = useSourceSink(null);
useEffect(() => {
const elem = source();
// ...
});
return (
Hello!
);
};
```### Why?
The following code does not pass the type check.
``` tsx
import React, { useRef } from "react";const Hello: React.FC = () => {
const ref = useRef(null);
return (
Hello!
);
};
```This is because a reference created by `useRef` is both readable and writable, and basically *invariant* in terms of types, which means it cannot be up- nor down-casted. A reference to `HTMLElement` cannot be passed to the `ref` prop of a `p` element, which requires a reference to `HTMLParagraphElement`.
To pass the type check, we can use a *callback ref*, which is basically *contravariant* and can be safely passed to a concrete element.
``` tsx
import React, { useRef, useCallback } from "react";const Hello: React.FC = () => {
const ref = useRef(null);
const callbackRef = useCallback((elem: HTMLElement | null): void => {
ref.current = elem;
}, []);
return (
Hello!
);
};
````useSourceSink` simplifies this boilerplate.
## License
[MIT License](http://opensource.org/licenses/mit-license.php)
## Author
Susisu ([GitHub](https://github.com/susisu), [Twitter](https://twitter.com/susisu2413))