changes as requested
Jared Forsyth committed
Dec 17, 2013 at 17:10 UTC
bf6951687d4b65a7a301b67563813e0efc7d34f9
1 file changed
+6
-10
docs/tips/10-props-in-getInitialState-as-anti-pattern.md
+6
-10
@@ -11,9 +11,9 @@ next: dom-event-listeners.html
11
>
12
> 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.
13
14
-Using props, passed down from parent, to generate state in `getInitialState` often leads to duplication of "source of truth", i.e. where the real data is (see [denormalization](http://en.wikipedia.org/wiki/Denormalization)). Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble. Javascript is plently fast for most use cases.
14
+Using props, passed down from parent, to generate state in `getInitialState` often leads to duplication of "source of truth", i.e. where the real data is. Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble.
15
16
-Bad example:
16
+**Bad example:**
17
18
```js
19
/** @jsx React.DOM */
@@ -61,15 +61,15 @@ var MessageBox = React.createClass({
61
React.renderComponent(<MessageBox name="Rogers"/>, mountNode);
62
```
63
64
-**But** in situations where your component truly is stateful, using props to initialize that state is totally fine. In such cases, it can be helpful to name the prop `initialX` (or similar) to make it clear that the state will not stay in sync.
65
-
66
-For example:
64
+However, it's **not** an anti-pattern if you intentionally make it clear that synchronization's not the goal here:
65
66
```js
67
/** @jsx React.DOM */
68
69
var Counter = React.createClass({
70
getInitialState: function() {
71
+ // naming it initialX clearly indicates that the only purpose
72
+ // of the passed down prop is to initialize something internal
73
return {count: this.props.initialCount};
74
},
75
handleClick: function() {
@@ -78,11 +78,7 @@ var Counter = React.createClass({
78
});
79
},
80
render: function() {
81
- return (
82
- <div onClick={this.handleClick}>
83
- {this.state.count}
84
- </div>
85
- );
81
+ return <div onClick={this.handleClick}>{this.state.count}</div>;
82
}
83
});
84