@zedux/react
Version:
A Molecular State Engine for React
25 lines (24 loc) • 1.22 kB
JavaScript
import React from 'react';
import { useEcosystem } from '../hooks/useEcosystem.js';
import { getReactContext } from '../utils.js';
/**
* Provides an atom instance over React context.
*
* Provided atom instances can be consumed in child components via
* `useAtomContext()`. The atom instance can then be passed to other hooks like
* `useAtomValue()` or `useAtomState()` to create a dynamic dependency on the
* consumed instance.
*
* The providing component should typically register at least a static
* dependency on the provided instance via `useAtomInstance()` or manual
* graphing inside `useEffect()`.
*/
export const AtomProvider = ({ children, instance, instances }) => {
const ecosystem = useEcosystem();
if (true /* DEV */ && !instance && !instances) {
throw new Error('Zedux: AtomProvider requires either an `instance` or `instances` prop');
}
const [nextInstance, ...childInstances] = instances || [instance];
const context = getReactContext(ecosystem, nextInstance.template);
return (React.createElement(context.Provider, { value: nextInstance }, childInstances.length ? (React.createElement(AtomProvider, { instances: childInstances }, children)) : (children)));
};