Redux Best Practices

martin rojas - Jan 9 '20 - - Dev Community

In 2019 there is still a very important place for Redux in developing larger web apps that have not been as established with the newer approaches. When advocating Redux, it is the architectural guidance that it provides to applications coming from Flux that I believe to still be so crucial.

flux architacture

The predictable flow of actions to a common store that then pushes the changes in React to update the view allows for predictable and debuggable sequences of operations that are easier to standardize in a team environment.

For every part of your code to which a project can have agreed upon guidelines will mean easier to understand code, a cleaner git history since every developer touching each file won't feel like they have to refactor to their own way.

mapStateToProps

mapStateToProps is a little confusing at first, but upon closer inspection, it is just a simple function (no imported library) that simply returns a specified part of the current state.

const mapStateToProps = (state) => {
     return { things: state.things }
};
Enter fullscreen mode Exit fullscreen mode

a valid alternative to make easier to read is to destructure the state

const mapStateToProps = ({ configuration }) => {
    return { colors: configuration.colors };
};
Enter fullscreen mode Exit fullscreen mode

mapDispatchToProps

Do this:

const mapDispatchToProps = {
  decrement: () => ({ type: "DECREMENT" }),
  increment: () => ({ type: "INCREMENT" }),
  getColors: params => getColors(params), //If passing variables to the action
};
Enter fullscreen mode Exit fullscreen mode

instead of this:

const mapDispatchToProps = dispatch => {
  return {
    decrement: () => dispatch({ type: "DECREMENT" }),
    increment: () => dispatch({ type: "INCREMENT" }),
  };
};
Enter fullscreen mode Exit fullscreen mode

The difference is that we rely on react-redux to inject dispatch on each value that is a function in our mapDispatchToProps object, rather than relying on react-redux to inject dispatch into our mapDispatchToProps function. This is the preferred way from the official react-redux documentation. https://react-redux.js.org/using-react-redux/connect-mapdispatch#defining-mapdispatchtoprops-as-an-object

connect()

When used with the Redux connect() function to export a component such as:

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
Enter fullscreen mode Exit fullscreen mode

we are exporting the combination of a component that is connected to the store. Think of connect() as the glue or interface between the component and the store. Any changes to the state will be reflected in the component because it is “connected” to mapStateToProps and that information is now made available to the component through a prop.

. . . . . . . . . . . . . . . . . .
Terabox Video Player