Eric Hth
Eric Hth

Reputation: 79

ReactJS: Initializing instance variable in component's getInitialState?

Is initializing component's instance variable in getInitialState relevant?

For example:

var Chat = React.createClass({

  getInitialState: function() {

    this.messages = []; // Instance variable initialization - EDIT: better as state variable?

    this.scrollToBottom = false; // EDIT - Instance variable which is not a state 

    return { 

       messages: [],

    };

  },

  componentDidUpdate: function() {

    if(this.scrollToBottom){

     // Animate DOM

     this.scrollToBottom = false;

    }

  },

  // ...

});

I would like to do that to make react component's code cleaner.

Thank you for helping

Upvotes: 1

Views: 2102

Answers (1)

Anders Ekdahl
Anders Ekdahl

Reputation: 22943

You can do that, but I would ask why you want to do that? What data would you store on the component that you don't want to store as state?

The point of putting it in the state is that React knows when you modify that state, and re-renders accordingly. If you define arbitrary properties on the instance React won't know about them.

Another good point about putting it in the state is that it makes it very easy to see where state is used and modified. Most bugs that occur in a component is related to state, so making the use of it obvious is really helpful.

Upvotes: 2

Related Questions