Constructor props state vs simply state

get derived state from props
react native constructor
react on props change
setstate react
displayname react
react native shouldcomponentupdate
componentdidmount setstate
this forceupdate

I started learning React when we could simply use state and create object instead of using constructor(props){ super(props)

Now, I see many libraries where they are still using

class Master extends Component {
  constructor(props){
    super(props)

So my first question is if there is an advantage of using constructor (props) super(props) and then setting up state? instead of just creating state object?

Second question, I wanted to implement react-native-slowlog in the native app I am making.

Throughout the code I have created the state object directly instead of using constructor.

The documentation for the react-native-slowlog shows this way to use it

class Master extends Component {
  constructor(props){
    super(props)
    slowlog(this, /.*/)

    this.state = this.getDataSource(props)
    this.shouldComponentUpdate = shouldComponentUpdate.bind(this)
  }
...
}

Where they call slowlog(this, /.*/) inside the constructor, so my question is can I avoid using constructor here? or is it okay if I create a constructor where I do slowlog(this, /.*/) and then create state object outside the constructor?

class Master extends Component {
  constructor(){
    super() 
    slowlog(this, /.*/)
  } 


  state = {
    searchCoin: false
  }

It's possible to skip explicit constructor if state is all you need to define, because this can be done with class fields proposal:

class Master extends Component {
  state = { searchCoin: false };
  ...

Which is syntactic sugar for ES6:

class Master extends Component {
  constructor(props){
    super(props);
    this.state = { searchCoin: false };
  } 
  ...

This is a matter of taste whether state is defined as class field or as a part of constructor body if there's a need for constructor; class field takes less characters to type because it doesn't contain this.

Also notice that

class Master extends Component {
  constructor(){
    super() 
    slowlog(this, /.*/)
  } 

  state = { searchCoin: false }
  ...

is syntactic sugar for

class Master extends Component {
  constructor(){
    super() 
    this.state = { searchCoin: false };
    slowlog(this, /.*/)
  } 
  ...

Class fields go after super and before other constructor statements. This may not work as intended if slowlog is expected to run first.

Props vs State in React, Props can be used to set the internal state based on a prop value in the constructor, like this: class ChildComponent extends React.Component  This is where state gets it’s initial data. The inital data can be hard coded (as above), but it can also come from props.. Well that’s just confusing. It is, I know. But it makes sense - you can’t change props, but it’s pretty reasonable to want to do stuff to the data that a component receives.

ReactJS: Props vs. State, This “props vs. state” question is pretty common for new React devs - they look so If Welcome is called without a name it will simply render <h1> Hello world</h1> . Component { constructor() { super(); this.state = { count: 0, };  Component { constructor (props) { super (props) this. state. colorName = props. color} } Of course a component can also initialize the state without looking at props. In this case there’s nothing useful going on, but imagine doing something different based on the prop value, probably setting a state value is best.

You only need to use the constructor if you are initializing state or binding functions.

If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component. https://reactjs.org/docs/react-component.html#constructor

So for what the library you linked to does, you do need to call it in the constructor. It both initializes the state and binds to the shouldComponentUpdate function.

However, if you aren't binding to anything you could always initialize the state directly on the property like this...

Typescript

class Master extends React.Component<any, any> {
  public readonly state = { someKey: "Initial Value" };
}

Javascript

class Master extends React.Component {
  state = { someKey: "Initial Value" };
}

Also I am not sure what the this.getDataSource(props) function does, and if that is just the example provided by slowlog. But initializing the state on the class property AND from the constructor won't wont. So you can do it like your example showed OR you could call that function from the componentDidMount function.

class Master extends React.Component {
  // initialize your state
  state = { someKey: "Initial Value" };

  constructor (props) {
    super(props)
    slowlog(this /*, */);

    this.shouldComponentUpdate = shouldComponentUpdate.bind(this);
  }

  componentDidMount() {
    const nextState = this.getDataSource(this.props);
    this.setState(nextState);
  }
}

On thing to note is that if getDataSource returns a promise, that should be called when the component mounts, rather than from the constructor.

If you need to load data from a remote endpoint, this is a good place to instantiate the network request. https://reactjs.org/docs/react-component.html#componentdidmount

Understanding Constructors with React Components ← Alligator.io, Simply put, the constructor aids in constructing things. handlers to the component and/or initializing the local state of the component. constructor(​props) { super(props); this.state = { reptile: 'alligator', color: '#008f68', }; }. React.Component is the base class for all class based ReactJS components. Whenever a class inherits the class React.Component it’s constructor will automatically assigns attribute state to the class with intial value is set to null. we can change it by overriding the method constructor. In many cases we need to update the state.

React State without Constructor, A tutorial on how to have state in React without a constructor in a access to the this object and therefore no access to this.state or this. That's how values can be passed to render props component; simply by using props. Initializing State from Props. In most cases, this is an antipattern. Don’t “copy props into state.” It creates a second source of truth for your data, which usually leads to bugs. One source of truth is best.

Storing data in state vs. class variable, constructor(props) { super(props) this.value = 'default' }. Later on, when he wanted to update the value stored on the object, he did with a simple  The React API is fairly simple, even though it has been growing bigger.With recent features such as Context and Hooks, the whole ecosystem has become more complete. Yet, some concepts are usually a source of struggle for beginners and even experienced developers.

React.Component – React, Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use componentDidMount() instead. Note. Avoid copying props into state  Even if you have class properties enabled, there might be times when you would want to base the initial state on props, and that would require use of a constructor. Also, normally you'd bind callback methods in a constructor., but if you're using class properties, you can define methods as arrow functions instead.

Comments
  • Since I haven't using constructor a lot, is it a good idea to call a redux action this.props.CurrencyRate() in constructor instead of componentDidMount and componentWillMount
  • This depends on how CurrencyRate works. componentWillMount is deprecated in favour of constructor. If it's async and works the same way in componentDidMount as it would in constructor then componentDidMount is the right place.
  • @KuchBhi don’t use constructor for Api calls. The main intention of providing constructor in React is to do Pre-initialling state and doing function/object bindings and accessing parent props when you want to pre-initialise the state with props from parent. You are recommended to do Api calls in componentDidMount and do setState accordingly.
  • I was under impression that OP wasn't interested in super() vs super(props), this was just pasted code, but that's a good point.
  • @estus that is okay, the lifecycle remains the same regardless of TS, Flow or JS. You can just remove the typing for the Class and State