Provider.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import React, { useMemo } from 'react';
  2. import PropTypes from 'prop-types';
  3. import { ReactReduxContext } from './Context';
  4. import { createSubscription } from '../utils/Subscription';
  5. import { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect';
  6. function Provider(_ref) {
  7. var store = _ref.store,
  8. context = _ref.context,
  9. children = _ref.children;
  10. var contextValue = useMemo(function () {
  11. var subscription = createSubscription(store);
  12. subscription.onStateChange = subscription.notifyNestedSubs;
  13. return {
  14. store: store,
  15. subscription: subscription
  16. };
  17. }, [store]);
  18. var previousState = useMemo(function () {
  19. return store.getState();
  20. }, [store]);
  21. useIsomorphicLayoutEffect(function () {
  22. var subscription = contextValue.subscription;
  23. subscription.trySubscribe();
  24. if (previousState !== store.getState()) {
  25. subscription.notifyNestedSubs();
  26. }
  27. return function () {
  28. subscription.tryUnsubscribe();
  29. subscription.onStateChange = null;
  30. };
  31. }, [contextValue, previousState]);
  32. var Context = context || ReactReduxContext;
  33. return /*#__PURE__*/React.createElement(Context.Provider, {
  34. value: contextValue
  35. }, children);
  36. }
  37. if (process.env.NODE_ENV !== 'production') {
  38. Provider.propTypes = {
  39. store: PropTypes.shape({
  40. subscribe: PropTypes.func.isRequired,
  41. dispatch: PropTypes.func.isRequired,
  42. getState: PropTypes.func.isRequired
  43. }),
  44. context: PropTypes.object,
  45. children: PropTypes.any
  46. };
  47. }
  48. export default Provider;