adding note about initializing state w/ props
Jared Forsyth committed
Dec 17, 2013 at 16:16 UTC
b5cfc72870c1d5d0cc248dfed8fda26aaef55bdc
1 file changed
+30
-2
docs/tips/10-props-in-getInitialState-as-anti-pattern.md
+30
-2
@@ -1,6 +1,6 @@
1
---
2
id: props-in-getInitialState-as-anti-pattern
3
-title: Using State to Cache Calculations Is an Anti-Pattern
3
+title: Props in getInitialState Is an Anti-Pattern
4
layout: tips
5
permalink: props-in-getInitialState-as-anti-pattern.html
6
prev: componentWillReceiveProps-not-triggered-after-mounting.html
@@ -11,7 +11,7 @@ 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 state to cache values calculated from props (for example 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.
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.
15
16
Bad example:
17
@@ -60,3 +60,31 @@ var MessageBox = React.createClass({
60
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:
67
+
68
+```js
69
+/** @jsx React.DOM */
70
+
71
+var Counter = React.createClass({
72
+ getInitialState: function() {
73
+ return {count: this.props.initialCount};
74
+ },
75
+ handleClick: function() {
76
+ this.setState({
77
+ count: this.state.count + 1
78
+ });
79
+ },
80
+ render: function() {
81
+ return (
82
+ <div onClick={this.handleClick}>
83
+ {this.state.count}
84
+ </div>
85
+ );
86
+ }
87
+});
88
+
89
+React.renderComponent(<Counter initialCount={7}/>, mountNode);
90
+```