Is this.state used in Constructor only?

I am learning a React, so, I want to know is this.state can be visible only in Constructor like most of the tutorial I have seen they use this.state on constructor

constructor() {
  super();
  this.state = {
    count: 0,
  };
}

So, whenever I initialize the state, I need to go with the constructor, I know we can do on functions too like event handler, but I am talking about class constructor?

I’ve only seen it used in React constructors.
https://facebook.github.io/react-vr/docs/components-props-and-state.html

Use this.state to initialize your state (in the constructor) and this.setState(newState) to update the state elsewhere in the app.

It is technically possible to mutate state using this.state= from anywhere within your app, but is discouraged, as it could lead to unexpected results.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.