"constructor" as an Anti-Pattern in React.Components

“The ties that bind us are stronger than the occasional stresses that separate us.”
― Colin Powell, It Worked for Me: In Life and Leadership

“The state assignments & bind calls in constructor are no longer worth the stress & should be separated from our code.”
James J. Womack, It Worked for Me: In Code and Componentry

Instead of getting poetic about what that means, I’ll show you an image:

Other than the class name, that’s real code from my employer. It’s an extreme case where way too much is going on in one component, but some version of that dance is happening in about half of the React components I’ve seen at Netflix.

I won’t get into the historical reasons folks have done that, and focus on the present. In the present, it’s not necessary if you’re using Babel to handle JSX.

Let’s take a less extreme example and refactor it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
export default class NewClusterPanel extends Component {
constructor(props) {
super(props)
this.onChildClick = this.onChildClick.bind(this)
this.onParentClick = this.onParentClick.bind(this)
this.state = {
search: ""
}
}
onParentClick(e, newValue) {
this.props.setUIProperty(this.props.uiProp, newValue)
}
onChildClick(e, newValue) {
this.props.setUIProperty(this.props.uiProp, newValue)
}
}

That’s a lot of noise in constructor just to set a default search string & ensure your methods contain “this”. Let’s try the same thing w/ stage 3 class properties:

1
2
3
4
5
6
7
8
9
10
11
export default class NewClusterPanel extends Component {
state = {
search: ""
}
onParentClick = (e, newValue) =>
this.props.setUIProperty(this.props.uiProp, newValue)
onChildClick = (e, newValue) =>
this.props.setUIProperty(this.props.uiProp, newValue)
}

Nice, huh? If you want to use this approach in your React projects, try npm i babel-preset-netflix-dea.

Later!