What is Redux mapStateToProps?
You are trying to figure out how the Redux connect function works, and you get stuck on one of the functions it takes as input: mapStateToProps
const mapStateToProps = (state) => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter),
}
}
This function selects parts of the Redux state and passes it in as props to the component that connect()
is applied to. That means that the structure of the state that your component gets, is not the same structure as the Redux state.
Now, why would you need this function? Why not pass in the whole Redux state?
Let’s look at an example.
You have a ProfilePicture
component that displays a profile picture.
If you don’t use connect, then you would pass in the whole store to this component
<ProfilePicture store={store} />
Now your ProfilePicture
component must know about the structure of the store. It must know how to fetch the profile picture URL from that store (for example store.user.profilePicture.url
).
Your components should only be concerned about displaying stuff. Now it also has to be concerned about finding data in the state.
The bad thing about this solution is that you cannot reuse the component in other places of your application. If you want to display the profile picture of something that is not a user, for example an event, you would need to create a new component for that.
mapStateToProps to the rescue!
Now let’s use the connect
function with mapStateToProps
function.
This time it’s the mapStateToProps
function that would know where to find the profile picture. And it would send only the URL to the ProfilePicture
component.
const mapStateToProps = (state) => {
return {
imgUrl: state.user.profilePicture.url,
}
}
connect(mapStateToProps)(ProfilePicture)
The ProfilePicture
component now only accepts imgUrl
as props, and you can use it in other parts of your application:
<ProfilePicture imgUrl={eventImgUrl} />
The Redux code is decoupled from your React components. Ahh. feels good to have such clean code!
Follow me on Twitter to get real-time updates with tips, insights, and things I build in the frontend ecosystem.