whyAto8
whyAto8

Reputation: 1670

React + Flux - How to avoid global variable

I have been working on React/Flux and am confused over the declaration of variable outside the component as in below code.

CounterComponent.js

var count;
function getCount (){

}
var CounterComponent = React.createClass({
  getInitialState: function(){
    return getCount();
  },
  render:function(){
  }
})
module.exports = CounterComponent;

As in the above code, the doubt is that the variable count and function getCount seem to be global here. Is it okay to have variables and functions declared here, outside the component or need to placed inside. This looks like global pollution.

Also, if we consider a store, have seen very examples as below, here also, the variable CHANGE_EVENT seem to be global, is that okay.

CounterStore.js

var CHANGE_EVENT = 'change';
var MainStore = assign({},EventEmitter.prototype, {
  AppDispatcher.register(function(payload){ 
    var action = payload.action;
    switch(action.actionType){        
    }
  });
});
module.exports = MainStore;

I have searched for this answer, but couldnt get the right answer. From javascript perspective it looks like its polluting global, but what about in React?

Upvotes: 1

Views: 686

Answers (1)

Kemal Dağ
Kemal Dağ

Reputation: 2763

It depends on the build system you use, if you use a system like browserify or webpack, then no variables would be global.

So if you do not use a bundler library, I suggest you to wrap your source code with a anonymous function, so that you wont pollute global namespace.

But I strongly suggest you to take a look with a modern approach using webpack which seems to be more popular within React and Flux community.

Upvotes: 2

Related Questions