Marin Veršić Marin Veršić - 29 days ago 21
React JSX Question

Defining attributes in React.js

I was wondering is there any difference between these two ways of defining React component attributes:

var something = React.createClass({
SSEStream: new EventSource("/stream/"),

componentDidMount: function() {
this.SSEStream.addEventListener("message", function(msg) {
// do something
}.bind(this));
});

var something = React.createClass({
componentDidMount: function() {
this.SSEStream = new EventSource("/stream/");

this.SSEStream.addEventListener("message", function(msg) {
// do something
}.bind(this));
}
});


Note the difference of how the React component attribute SSEStream was defined. My guess is that in the second example attribute is being recreated every time component is re-rendered whereas in the first it is created only once and therefore the first way should be preferred.

So the question is, will there be even the slightest difference between the two?

Answer

The difference between the two is as follows:

The first instantiates and sets a single EventSource at the time the component is declared, which is shared between each instance of the component.

On the other hand, the second creates a separate EventSource for each instance of the component, when the callback is fired.

Assuming that you want multiple instances of the component to be independent of one another, then I guess that the second option is what you want.

By the way, the componentDidMount callback is typically only run once in the life-cycle of the component, when the component is first mounted, so this has nothing to do with re-renders.