Skip to content
This repository has been archived by the owner on Feb 2, 2024. It is now read-only.
/ preact-pair Public archive

πŸ–‡οΈ Util to help with the paired hook pattern

License

Notifications You must be signed in to change notification settings

vangware/preact-pair

Repository files navigation

This repository's code was moved to lou.codes.


Coverage License NPM Version Open Issues

πŸ–‡οΈ Util to help with the paired hook pattern.

Usage

πŸ“¦ Node

Install preact-pair as a dependency:

pnpm add preact-pair
# or
npm install preact-pair
# or
yarn add preact-pair

Import it and use it:

import { useState } from "preact";
import { pair } from "preact-pair";

const useCount = initialCount => {
	const [count, setCount] = useState(initialCount);

	return { onClick: () => setCount(count + 1), children: count };
};

const PairedCount = pair(useCount);

const Component = ({ array = [] }) => (
	<ul>
		{array.map(key => (
			<PairedCount key={key}>
				{usePairedCount => {
					const props = usePairedCount(key);

					return (
						<li>
							<button type="button" {...props} />
						</li>
					);
				}}
			</PairedCount>
		))}
	</ul>
);

πŸ¦• Deno

Import preact-pair using the npm: prefix, and use it directly:

import { useState } from "npm:preact";
import { pair } from "npm:preact-pair";

const useCount = initialCount => {
	const [count, setCount] = useState(initialCount);

	return { onClick: () => setCount(count + 1), children: count };
};

const PairedCount = pair(useCount);

const Component = ({ array = [] }) => (
	<ul>
		{array.map(key => (
			<PairedCount key={key}>
				{usePairedCount => {
					const props = usePairedCount(key);

					return (
						<li>
							<button type="button" {...props} />
						</li>
					);
				}}
			</PairedCount>
		))}
	</ul>
);

🌎 Browser

Import preact-pair using esm.sh, and use it directly:

<script type="module">
	import { h, useState } from "https://esm.sh/preact";
	import { pair } from "https://esm.sh/preact-pair";

	const useCount = initialCount => {
		const [count, setCount] = useState(initialCount);

		return { onClick: () => setCount(count + 1), children: count };
	};

	const PairedCount = pair(useCount);

	const Component = ({ array = [] }) => (
		<ul>
			{array.map(key =>
				h(PairedCount, { key }, usePairedCount => {
					const props = usePairedCount(key);

					return h("li", null, h("button", props));
				}),
			)}
		</ul>
	);
</script>

Useful links