UNPKG

dreamstate

Version:

Store management library based on react context and observers

44 lines (41 loc) 1.75 kB
import { useContext } from 'react'; import { createScopedProviderTree } from './createScopedProviderTree.js'; import { ScopeContext } from '../../scoping/ScopeContext.js'; /** * Creates a provider that bundles all observers into scoped nodes, ensuring minimal re-renders. * * This function generates a React provider component that groups all specified context managers into scoped * nodes. It efficiently updates only the affected provider when changes occur, preventing unnecessary re-renders * for the entire provider tree. This optimization helps improve performance by limiting updates to only the * parts of the tree that require them. * * @template T - The type of the provider props. * @param {Array<TAnyContextManagerConstructor>} sources - An array of context manager class references * that should be provided as context within scoped nodes. * @returns {FunctionComponent<IProviderProps<T>>} A React function component that acts as a scoped provider * for the specified context manager classes, optimizing re-renders. */ function createScopedProvider(sources) { function Provider(props) { var scope = useContext(ScopeContext); /* * Warn if current observer is mounted out of scope in dev mode. */ { if (!scope) { console.error("[DS]", "Dreamstate providers should be used in a scope. Wrap your component tree with ScopeProvider"); } } return createScopedProviderTree(sources, props, scope); } /* * Single wrapper, many observers + providers in isolated scopes. */ { Provider.displayName = "Dreamstate.ScopedProviders[".concat(sources.map(function (it) { return it.name; }), "]"); } return Provider; } export { createScopedProvider };