tommyd456 tommyd456 - 23 days ago 6
React JSX Question

Are multiple objects being created?

I'm working on a simple React library but I'm unsure whether multiple objects are being created unnecessarily.

I have an

app.js
file:

class App {
method1() {

}
method2() {

}
}
export default new App();


I also have an
index.js
file:

import app from './app.js';
...
export default app;


In the
index.js
of my React project (where I make use of the library) I use:

import MyLibrary from 'react-library';
...
MyLibrary.method1();


and then I do the same in some of my components too:

import MyLibrary from 'react-library';
...
MyLibrary.method2();


Is the second import of
MyLibrary
a different object to the first
MyLibrary
?

Answer Source

Is the second import of MyLibrary a different object to the first MyLibrary?

In general the object returned by the import is cached (same behaviour as nodejs require), multiples import of the same file will result in the same object being returned. So the answer to your question is No, you're dealing with the same reference in memory.

https://webpack.github.io/docs/resolving.html

Every filesystem access is cached so that multiple parallel or serial requests to the same resource are merged.

in your particular case, as suggested in the comments section, you're exporting an instance, not the class itself

export default new App();

consequently each component that import that file will deal with the same instance. This is a singleton pattern, don't know if it is the desired behaviour, if you want that each component has it's own instance you should export the class instead.

export default App;