Replacing mapStateToProps with the useSelector Hook

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

Redux provides a useSelector hook for easy access to state within a function component. This hook replaces the mapStateToProps function which was used previously with connect(). The hooks API is a lot simpler and can be combined nicely with selector functions.

The basic API looks like this:

const value = useSelector(state => state.reducerName.value)

When used with a selector function it looks like this:

const value = useSelector(getValue)

Jamund Ferguson: [0:00] At the top of ExchangeRate.js, import { useSelector } from "react-redux". Then, scroll down to the bottom of the component and copy over the body of the mapStateToProps() function. Go ahead and paste that at the top of your component.

[0:13] For each of these, in front of the key name type const and replace the colon with an equal sign, and then add useSelector(state =>) and then the selection name, getSupportedCurrencies, or in this case, useSelector(state => getCurrencyCode). Make sure to remove the comma at the end.

[0:34] This is the essence of the useSelector hook. It takes a function, which receives state from the Redux store, and then it can pass that state to a selector function, such as getCurrencyCode. There's even a shorthand way to write this, where we can say useSelector and then pass in the selector function directly.

[0:50] We don't have to use selector functions, though, if we wanted, we could call state.rates.supportedCurrencies and pull that directly in here, if we'd like. For me, I prefer to use the selector. It's a lot cleaner, so we'll type useSelector(getSupportedCurrencies) and useSelector(getCurrencyCode).

[1:05] Now, with supportedCurrencies and currencyCode as variables, we no longer need them as props. Let's go ahead and remove both of those, and you can see that the app continues to work as expected, but if we go down here, we can now remove the PropTypes. We no longer need currencyCode or supportedCurrencies.

[1:22] We can even remove the mapStateToProps function. We don't need that anymore either. We can replace it within our connect call with a simple null.

Matt
Matt
~ 2 years ago

This seems like it would complicate testing a component vs the older pattern of a separate mapStateToProps(). When you remove props from a component and rely on global hooks, you have more work to do when mocking those usages.

Markdown supported.
Become a member to join the discussionEnroll Today