edmamerto
edmamerto

Reputation: 8165

Mapping state to props in Redux

Would it be a bad practice to make mapped stateProps into constructorStates?

To make my question more clear her is an Example:

//some class
  constructor(props) {
    super(props);
    this.props.getMessages(1)     
    this.state = {
      messages: this.props.messages
    };
  }

function mapStateToProps(state) {
  return {
    messages: state.messages
  };
}

In example above, I know I could use this.props.messages raw style, but I see some examples that makes props into a state.

Another example i got from code pen:

  constructor(props) {
    super(props);
    this.state = {
      step: props.initialStep, 
      count: props.initialCount     
    };       
  }

Counter.propTypes = { initialCount: React.PropTypes.number };
Counter.defaultProps = { initialStep: 5, initialCount: 0 };

So what is the point of differentiating props to state when you some people try to make props a state?

Upvotes: 1

Views: 548

Answers (2)

Eric Levine
Eric Levine

Reputation: 13564

One way to think about Redux, is that it contains and manages the state for your entire application. Your Components should merely reflect this state, not change it directly, which is why you want to get it into your props. If in addition your Component needs to maintain some extra state, then you can make a case to use state directly and not worry about passing it through Redux.

Upvotes: 0

Brigand
Brigand

Reputation: 86240

You should only do this when you want to detach the local state from the global state.

For example, if you're making a form, you don't want the values to be replaced when the store updates.

In general, don't copy props into state. It's a common source of bugs. One of the less obvious bugs is that the state might not exist at the time the component mounts, e.g. if you're fetching it from a http api.

Upvotes: 2

Related Questions