useDispatch.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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 = ReactReduxContext) {
  10. const useStore = // @ts-ignore
  11. context === ReactReduxContext ? useDefaultStore : createStoreHook(context);
  12. return function useDispatch() {
  13. const store = useStore(); // @ts-ignore
  14. return store.dispatch;
  15. };
  16. }
  17. /**
  18. * A hook to access the redux `dispatch` function.
  19. *
  20. * @returns {any|function} redux store's `dispatch` function
  21. *
  22. * @example
  23. *
  24. * import React, { useCallback } from 'react'
  25. * import { useDispatch } from 'react-redux'
  26. *
  27. * export const CounterComponent = ({ value }) => {
  28. * const dispatch = useDispatch()
  29. * const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), [])
  30. * return (
  31. * <div>
  32. * <span>{value}</span>
  33. * <button onClick={increaseCounter}>Increase counter</button>
  34. * </div>
  35. * )
  36. * }
  37. */
  38. export const useDispatch = /*#__PURE__*/createDispatchHook();