useDispatch.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { ReactReduxContext } from '../components/Context';
  2. import { useStore as useDefaultStore, createStoreHook } from './useStore';
  3. /**
  4. * Hook factory, which creates a `useDispatch` hook bound to a given context.
  5. *
  6. * @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`.
  7. * @returns {Function} A `useDispatch` hook bound to the specified context.
  8. */
  9. export function createDispatchHook(context) {
  10. if (context === void 0) {
  11. context = ReactReduxContext;
  12. }
  13. var useStore = context === ReactReduxContext ? useDefaultStore : createStoreHook(context);
  14. return function useDispatch() {
  15. var store = useStore();
  16. return store.dispatch;
  17. };
  18. }
  19. /**
  20. * A hook to access the redux `dispatch` function.
  21. *
  22. * @returns {any|function} redux store's `dispatch` function
  23. *
  24. * @example
  25. *
  26. * import React, { useCallback } from 'react'
  27. * import { useDispatch } from 'react-redux'
  28. *
  29. * export const CounterComponent = ({ value }) => {
  30. * const dispatch = useDispatch()
  31. * const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), [])
  32. * return (
  33. * <div>
  34. * <span>{value}</span>
  35. * <button onClick={increaseCounter}>Increase counter</button>
  36. * </div>
  37. * )
  38. * }
  39. */
  40. export var useDispatch = /*#__PURE__*/createDispatchHook();