@zedux/react
Version:
A Molecular State Engine for React
44 lines (43 loc) • 1.89 kB
JavaScript
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import { createEcosystem } from '@zedux/atoms';
import React, { useEffect, useMemo } from 'react';
import { ecosystemContext } from '../utils.js';
/**
* EcosystemProvider
*
* If an `ecosystem` prop is passed, that ecosystem will take charge of all atom
* usages below it in the component tree.
*
* If no `ecosystem` prop is passed, EcosystemProvider creates an atom ecosystem
* and provides it. The created ecosystem will be destroyed when this
* EcosystemProvider unmounts. The auto-created ecosystem can be configured with
* props passed here.
*
* ```ts
* // gives you full control over the ecosystem:
* <EcosystemProvider ecosystem={ecosystem}>
*
* // a convenient shorthand, esp. useful in testing:
* <EcosystemProvider id="root">
* ```
*/
export const EcosystemProvider = (_a) => {
var { children, ecosystem: passedEcosystem } = _a, ecosystemConfig = __rest(_a, ["children", "ecosystem"]);
const ecosystem = useMemo(() => passedEcosystem ||
createEcosystem(Object.assign({ destroyOnUnmount: true }, ecosystemConfig)), [ecosystemConfig.id, passedEcosystem]); // don't pass other vals; just get snapshot when these change
useEffect(() => {
ecosystem._incrementRefCount();
return () => ecosystem._decrementRefCount();
}, [ecosystem]);
return (React.createElement(ecosystemContext.Provider, { value: ecosystem.id }, children));
};