Props in getInitialState Is an Anti-Pattern

Note:

This isn’t really a React-specific tip, as such anti-patterns often occur in code in general; in this case, React simply points them out more clearly.

Using props to generate state in getInitialState often leads to duplication of “source of truth”, i.e. where the real data is. This is because getInitialState is only invoked when the component is first created.

Whenever possible, compute values on-the-fly to ensure that they don’t get out of sync later on and cause maintenance trouble.

Bad example:

  1. var MessageBox = React.createClass({
  2. getInitialState: function() {
  3. return {nameWithQualifier: 'Mr. ' + this.props.name};
  4. },
  5. render: function() {
  6. return <div>{this.state.nameWithQualifier}</div>;
  7. }
  8. });
  9. ReactDOM.render(<MessageBox name="Rogers"/>, mountNode);

Better:

  1. var MessageBox = React.createClass({
  2. render: function() {
  3. return <div>{'Mr. ' + this.props.name}</div>;
  4. }
  5. });
  6. ReactDOM.render(<MessageBox name="Rogers"/>, mountNode);

(For more complex logic, simply isolate the computation in a method.)

However, it’s not an anti-pattern if you make it clear that the prop is only seed data for the component’s internally-controlled state:

  1. var Counter = React.createClass({
  2. getInitialState: function() {
  3. // naming it initialX clearly indicates that the only purpose
  4. // of the passed down prop is to initialize something internally
  5. return {count: this.props.initialCount};
  6. },
  7. handleClick: function() {
  8. this.setState({count: this.state.count + 1});
  9. },
  10. render: function() {
  11. return <div onClick={this.handleClick}>{this.state.count}</div>;
  12. }
  13. });
  14. ReactDOM.render(<Counter initialCount={7}/>, mountNode);