useReduxContext.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { useContext } from 'react';
  2. import { ReactReduxContext } from '../components/Context';
  3. /**
  4. * Hook factory, which creates a `useReduxContext` hook bound to a given context. This is a low-level
  5. * hook that you should usually not need to call directly.
  6. *
  7. * @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`.
  8. * @returns {Function} A `useReduxContext` hook bound to the specified context.
  9. */
  10. export function createReduxContextHook(context = ReactReduxContext) {
  11. return function useReduxContext() {
  12. const contextValue = useContext(context);
  13. if (process.env.NODE_ENV !== 'production' && !contextValue) {
  14. throw new Error('could not find react-redux context value; please ensure the component is wrapped in a <Provider>');
  15. }
  16. return contextValue;
  17. };
  18. }
  19. /**
  20. * A hook to access the value of the `ReactReduxContext`. This is a low-level
  21. * hook that you should usually not need to call directly.
  22. *
  23. * @returns {any} the value of the `ReactReduxContext`
  24. *
  25. * @example
  26. *
  27. * import React from 'react'
  28. * import { useReduxContext } from 'react-redux'
  29. *
  30. * export const CounterComponent = () => {
  31. * const { store } = useReduxContext()
  32. * return <div>{store.getState()}</div>
  33. * }
  34. */
  35. export const useReduxContext = /*#__PURE__*/createReduxContextHook();