Skip to content

Commit 3d2f182

Browse files
committed
➕ Props in Initial State is an Anti-pattern
1 parent ec56009 commit 3d2f182

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
---
2+
id: props-in-initial-state-is-an-anti-pattern
3+
sidebar_label: Props in initial state is an anti-pattern
4+
title: Props in Initial State is an Anti-pattern
5+
description: Props in initial state is an anti-pattern | React Patterns, techniques, tips and tricks in development for Ract developer.
6+
keywords: ['props in initial state is an anti-pattern', 'reactpatterns', 'react patterns', 'reactjspatterns', 'reactjs patterns', 'react', 'reactjs', 'react techniques', 'react tips and tricks']
7+
version: Props in initial state is an anti-pattern
8+
image: /img/reactpatterns-cover.png
9+
---
10+
11+
Using props to generate state in constructor ( or getInitialState) often leads to duplication of "source of truth", for example where the real data is. This is because constructor (or getInitialState) is only invoked when the component is first created.
12+
13+
The danger is that if the props on the component are changed without the component being 'refreshed', the new prop value will never be displayed because the constructor function (or getInitialState) will never update the current state of the component. The initialization of state from props only runs when the component is first created.
14+
15+
The bad one.
16+
17+
```jsx
18+
class UserPassword extends Component {
19+
// Constructor (or getInitialState)
20+
constructor(props) {
21+
super(props)
22+
this.state = {
23+
confirmed: false,
24+
inputVal: props.inputValue
25+
}
26+
}
27+
28+
render() {
29+
return <div>{this.state.inputVal && <AnotherComponent/>}</div>
30+
}
31+
}
32+
```
33+
34+
The good one.
35+
36+
```jsx
37+
class UserPassword extends Component {
38+
// Constructor function (or getInitialState)
39+
constructor(props) {
40+
super(props);
41+
this.state = {
42+
confirmed: false
43+
}
44+
}
45+
46+
render() {
47+
return <div>{this.props.inputValue && <AnotherComponent/>}</div>
48+
}
49+
}
50+
```

sidebars.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,5 +38,8 @@ module.exports = {
3838
'state-hoisting',
3939
'pure-component-avoid-heavy-rerender',
4040
],
41+
'React Anti-patterns': [
42+
'props-in-initial-state-is-an-anti-pattern',
43+
],
4144
},
4245
};

0 commit comments

Comments
 (0)