The 2 Maps
At first glance, React/Redux is very intimidating. In particular, the handling of props confused me because my logic assumed that a child component would know its own properties and not need them handed down. So I didn’t understand the difference between what I referred to as the 2 maps; mapStateToProps and mapDispatchToProps. Using the connect function is mandatory for both which I assumed meant they were doing pretty much the same thing. Since I didn’t perceive their differences, I couldn’t determine which one to use when or why. So I turned to the documentation.
Documentation for mapStateToProps: “It is called every time the store state changes.” (https://react-redux.js.org/using-react-redux/connect-mapstate)
Documentation for mapDispatchToProps: “This is the only way to trigger a state change.” (https://react-redux.js.org/using-react-redux/connect-mapdispatch)
Of course there was more in the documentation but I focused on the two statements above and they are practically identical to me. The 2 maps are both messing around with the state!
I decided to see what Stack Overflow had to say on the subject and turned up the following: “mapStateToProps is a function that you would use to provide the store data to your component, whereas mapDispatchToProps is something that you will use to provide the action creators as props to your component.” (https://stackoverflow.com/questions/49994197/whats-the-difference-between-mapstatetoprops-and-mapdispatchtoprops)
Finally, a bit of clarity. So mapStateToProps solely provides store data to the component while mapDispatchToProps solely provides action creators to the component. The store data reflects the current store state and action creators are function calls to functions that contain a fetch request.
I consulted the documentation again and came across this section: “Behavior and Gotchas mapStateToProps Will Not Run if the Store State is the Same” (https://react-redux.js.org/using-react-redux/connect-mapstate)
More clarity! So mapStateToProps is NOT changing the state, it’s just accessing it for data to pass as a prop to be rendered (displayed). While mapDispatchToProps only changes the state (data), it does NOT display it.
I re-read my initial 2 documentation statements and I could now clearly see their subtle differences. True, both functions are “messing around with the state” but…
— mapStateToProps is called every time the store state changes so it can be re-rendered (NOT to change the store state)
— mapDispatchToProps is the only way to trigger a state change which updates (changes) the store data (but does NOT render it)
React was a lot less intimidating after I understood the 2 map processes and was able to accurately track the flow of data through a React app. Now I’m looking forward to building more React apps to sharpen my skills and gain greater insight.