Replacing mapDispatchToProps with the useDispatch Hook

Jamund Ferguson
InstructorJamund Ferguson

Share this video with your friends

Send Tweet

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.