Replacing mapDispatchToProps with the useDispatch Hook

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

Redux provides a useDispatch hook to make it easy to dispatch actions within a function component. This hook replaces the mapDispatchToProps function which was used previously with connect().

The basic API looks like this:

const dispatch = useDispatch();

Within a component you can choose to use dispatch() directly, within an event handler for example, or create a function to that dispatches the action and reference that. This lesson shows both options.

Jamund Ferguson: [0:00] At the top of ExchangeRate.js, import { useDispatch } from "react-redux". Then, at the top of our component, type const dispatch = useDispatch(). This hook gives us a dispatch function that we can use to dispatch actions into our Redux store.

[0:18] If you go down to the bottom of the file, you can see our mapDispatchToProps() function, which we pass into connect. Go ahead and copy the contents of our updateRates() function, which is here, dispatch(ratesUpdated(rates)), and now, where we were previously calling updateRates, we can now call dispatch(ratesUpdated(rates)).

[0:39] Or, if we prefer, we can remove the prop and create a function called const updateRates = (rates), and then, when that's received, dispatch(ratesUpdated(rates)). We've now removed all of the props that we had with the useDispatch hook.

[0:56] We no longer need mapDispatchToProps, and we can remove that function and replace it with null in our connect method. We could also remove our propTypes as they aren't needed any longer.

[1:08] Now we have a significantly simpler component that's just as powerful.

egghead
egghead

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today