Provider.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import * as React from 'react';
  2. import { ReactReduxContext } from './Context';
  3. import { createSubscription } from '../utils/Subscription';
  4. import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect';
  5. function Provider({
  6. store,
  7. context,
  8. children,
  9. serverState,
  10. stabilityCheck = 'once',
  11. noopCheck = 'once'
  12. }) {
  13. const contextValue = React.useMemo(() => {
  14. const subscription = createSubscription(store);
  15. return {
  16. store,
  17. subscription,
  18. getServerState: serverState ? () => serverState : undefined,
  19. stabilityCheck,
  20. noopCheck
  21. };
  22. }, [store, serverState, stabilityCheck, noopCheck]);
  23. const previousState = React.useMemo(() => store.getState(), [store]);
  24. useIsomorphicLayoutEffect(() => {
  25. const {
  26. subscription
  27. } = contextValue;
  28. subscription.onStateChange = subscription.notifyNestedSubs;
  29. subscription.trySubscribe();
  30. if (previousState !== store.getState()) {
  31. subscription.notifyNestedSubs();
  32. }
  33. return () => {
  34. subscription.tryUnsubscribe();
  35. subscription.onStateChange = undefined;
  36. };
  37. }, [contextValue, previousState]);
  38. const Context = context || ReactReduxContext; // @ts-ignore 'AnyAction' is assignable to the constraint of type 'A', but 'A' could be instantiated with a different subtype
  39. return /*#__PURE__*/React.createElement(Context.Provider, {
  40. value: contextValue
  41. }, children);
  42. }
  43. export default Provider;