MAPSTATETOPROPS & MAPDISPATCHTOPROPS: The Bad Boys of React-Redux
During my journey with react, I found a concept difficult to grasp and I see new react developers struggle with it. Which concept am I talking about? I am talking about the mapstatetoprops and mapdispatchtoprops concept. At first, when I came across it, I asked myself what are we mapping? why do we need that code? what goes in it? Well, we will break it down here.
Before we dive in, there are some ideas you need to be familiar with.
Understanding of react.
Familiarity with redux store.
Understanding react actions.
Understanding react reducers.
Familiarity with these concepts will make the article make more sense.
In react, components has state. But their state is scoped for themselves and inner components. Also, their state gets refreshed when reloaded. This will be a problem when you need to store states for the whole application. States that will be accessible to all components and editable by them. Redux is here for you. Redux keeps state for your entire application with the help of its store. Components can request and perform actions to the Redux store state. An important note is that the redux store only changes its state when an action is dispatched. That is, you can only change a redux state by sending an action to the store dispatch function. This helps unify the way the store can be changed.
Mapstatetoprops is a function that takes a parameter and returns an object, this parameter is the redux store state. It injects the state into the function under the hood. It returns an object which will hold all the state you need in your component props. This object will be an object of values. Lets take for example :
Assume that this our redux store state.
To change a redux state, we send actions to the redux store dispatch function. but how do we get the redux dispatch function? mapdispatchtoprops helps with that. mapdispatchtoprops is a function that takes redux store dispatch function as a parameter. And returns an object of functions. these object which it returns hold all the functions you need to inject into the component props.
Let’s take an example, we have an action :
We have been talking about mapstatetoprops and mapdispatchtoprops, but how do these functions get the redux store state and dispatch function? Here comes the connect function. The connect function is the link that provides the redux state and dispatch function. That is, if we don’t have the connect function in our component, mapstatetoprops, and mapdispatchtoprops won’t work. Sample of connect function.