Why should I declare vars, lets and consts inside a class, and require my entire class to use the keyword this
to refer to these variables, instead of just at the top of the file before the class, to avoid the need to use this
. I get the point of instance variables for a class I will reuse multiple times, but if it is just a page to my website, is there any need to declare variables within the class. Thanks.

- 474
- 5
- 14
-
If you use variable outside and when you override variable values your component won’t re-render and you won’t be able to see updated values. It’s good to play with component states to override values so that they render and shows updated values – Hemadri Dasari Oct 16 '18 at 19:09
-
Possible duplicate of [I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?](https://stackoverflow.com/questions/2613310/ive-heard-global-variables-are-bad-what-alternative-solution-should-i-use) – Mark Schultheiss Oct 16 '18 at 19:10
-
1"*require my entire class to use the keyword `this` to refer to these variables*" - I don't follow. `this.…` will refer to a *property* of an instance, not to a variable. What exactly are you talking about? – Bergi Oct 16 '18 at 19:14
-
1You want to create hard to debug code just because you can save a few extra `this.` ? why? – Jonas Wilms Oct 16 '18 at 19:14
-
@bergi as far as I understood, he got a Singleton and wants to turn its properties into global variables to save a few bytes. – Jonas Wilms Oct 16 '18 at 19:15
-
@JonasWilms Well if he wants a singleton, starting with a `class` was the wrong thing. – Bergi Oct 16 '18 at 19:16
-
@bergi I guess thats not possible as React.createElement takes a class / constructor – Jonas Wilms Oct 16 '18 at 19:18
-
Yea, I know the class is dumb, but yes as @JonasWilms said, React make it so that I have to use a class. And Jonas, why does this make it harder to debug? I guess it will be known to the file but not the class. I am more wondering from a theoretical/curiosity perspective, but saving a couple this' would be cool if it didn't hurt/ there was so no difference. – Young Scooter Oct 16 '18 at 21:40
-
@YoungScooter there is e.g. the React Developer tools that shows the current state / props inside a component tree ... if you store it outside you won't see it – Jonas Wilms Oct 17 '18 at 16:59
1 Answers
It is a matter of shared memory (closure and context).
When you use the instance to store data (and referring it via this
), then you can't preserve the data across mounting (when component is re-mounted).
When you use the "external" variable, the data will persist.
Here is a small example, just click the button couple of times and see how the number of the external variable increase while the instance variable gets reset on each mount :
let externalCounter = 0;
class Test extends React.Component {
componentDidMount() {
externalCounter += 1;
this.myCounter += 1;
}
myCounter = 0;
render() {
return <div>{`external counter is ${externalCounter} and myCounter is ${
this.myCounter
}`}</div>;
}
}
class App extends React.Component {
state = { mount: true };
toggleMount = () => this.setState(({ mount }) => ({ mount: !mount }));
render() {
const { mount } = this.state;
return (
<div>
<button onClick={this.toggleMount}>toggle mount</button>
{mount && <Test />}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />
Of course i'm under the impression you are using some sort of modules exports and the "external" variable is declared at the module scope.
Edit
As a followup to your comments and questions bellow:
so two classes in separate files. One parent, one child. The child's module level variable will not persist across mounting and mounting.
This is not quite true.
Given this module:
let externalCounter = 0;
class Test extends React.Component {
componentDidMount() {
externalCounter += 1;
this.myCounter += 1;
}
myCounter = 0;
render() {
return <div>{`external counter is ${externalCounter} and myCounter is ${
this.myCounter
}`}</div>;
}
}
export defualt Test;
Think of it as a big function that have a nested function:
function SomeModule(){
let externalCounter = 0;
function Test(props){
// some logic
}
return Test;
}
When you import Test
in another module (file) you actually grabbing the inner function Test
and it will get re-invoked whenever react will re-mount this component, but it doesn't mean the SomeModule
function will get re-invoked, it won't. hence the externalCounter
will persist data across calls of the Test
function.
This is actually a closure.

- 30,379
- 9
- 68
- 99
-
This is a great example. Thank you very much. It seems that these "global" variables would only apply when I have two classes in the same file. As of now, I am making it so I have one class per file, so it doesn't seem like the choice matters much. – Young Scooter Oct 16 '18 at 21:37
-
@YoungScooter these are not global to the application level but global to the module. A module after bundling will be a function, the class will be an inner function which will close over that variable. So the most popular use case for it is to persist data across instances while keeping it hidden to other modules. – Sagiv b.g Oct 17 '18 at 05:04
-
In my example think that `App` is on a different file. I couldn't do it here with stack snippets. But it will behave the same – Sagiv b.g Oct 17 '18 at 06:08
-
right. How would you define a module though? If I have two files with two different classes in each. A is the parent of B. B has a class variable and an "outside" variable such as yours. When A renders B and increments both values, they are the same, but when B unmounts and remounts such as in your example, the values are still the same. The value does not persist since the variable in part of the file which is unmounted. – Young Scooter Oct 17 '18 at 13:08
-
-
The module is not unmounting, the react class is. If the variable is inside that module file (with no export) no other module or function outside this file can access it, only functions inside this file. – Sagiv b.g Oct 17 '18 at 13:10
-
I think my issue is I am exporting the default class name. Maybe this is wiping the memory of the outer/module variables? – Young Scooter Oct 17 '18 at 13:12
-
I may confused you, but i'm calling the file a module. The things we export from this file are the public keys of this module. – Sagiv b.g Oct 17 '18 at 13:12
-
so two classes in separate files. One parent, one child. The child's module level variable will not persist across mounting and mounting. Think I should probably take advantage of this instead of staying in the pattern of creating one class in a file, and that's the entire file. Thanks for clarification though, think I get it better now. – Young Scooter Oct 17 '18 at 13:18
-
If the variable is outside the child's class it will persist. Think of it as the file is one big function and the class is a nested function which will get invoked on each re-mount. The outer variable persist as the outer function wasn't re-invoked. This called closure. – Sagiv b.g Oct 17 '18 at 14:20
-
1I see it now. I don't know what I was missing before, but it is persiting after unmount & remount. Leading to lots of little bugs and errors that would destroy me later. Thanks so much. – Young Scooter Oct 17 '18 at 17:12