Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to define state in constructor or using property initializers?

According to this babel documentation, the correct way to use ES6+ with React is to initial components like this:

class Video extends React.Component {   static defaultProps = {     autoPlay: false,     maxLoops: 10,   }   static propTypes = {     autoPlay: React.PropTypes.bool.isRequired,     maxLoops: React.PropTypes.number.isRequired,     posterFrameSrc: React.PropTypes.string.isRequired,     videoSrc: React.PropTypes.string.isRequired,   }   state = {     loopsRemaining: this.props.maxLoops,   } } 

But some official examples, like Dan Abramov's own React DnD module, uses ES6+ but still defines state within the constructor:

constructor(props) {     super(props);     this.moveCard = this.moveCard.bind(this);     this.state = {        // state stuff     } } 

Now Dan Abramov, being a significant contributor to React, probably knows that he can define state outside the constructor, yet still opts to do it within the constructor.

So I'm just wondering which way is better and why?

like image 318
abustamam Avatar asked Jun 13 '16 11:06

abustamam


People also ask

What is the best place to initialize state?

One way is to initialize the state is in the constructor. As we discussed earlier constructor is the first method to be called when React instantiates the class. This is the perfect place to initialize the state for the component because the constructor is called before the React renders the component in the UI.

Can you set state in constructor?

setState can't be called in constructor. Because setState is async. It can result unexpected behavior if you were trying to get or modify this.

Should I use props or state?

Props are used to pass data, whereas state is for managing data. Data from props is read-only, and cannot be modified by a component that is receiving it from outside. State data can be modified by its own component, but is private (cannot be accessed from outside)


1 Answers

I believe it's a matter of personal preference. The transpiled output is the same in terms of semantics.

  • Class Property
  • Constructor
like image 71
ctrlplusb Avatar answered Sep 19 '22 12:09

ctrlplusb