Memory when importing js objects in react

Viewed 419

I am new to react and its transpiled way of generating javascript.

In react side, I have a class Utility that uses a data object UserData organized as below -

UserDataObj.js

class UserData{
  this.someobj = {};
  //some function here
  something(){

  }
}

const UserDataObj = new UserData();
export {UserDataObj};

Utility.js

import {UserDataObj} from './data/UserDataObj';
class Utility {
    doSomething(){
      //UserDataObj.something();
    }
}
const utility = new Utility();
export {utility};

I have another ReactApp UserApp.js, that also uses UserDataObj and Utility (although not good design wise) -

import {UserDataObj} from './data/UserDataObj';
import {utility} from './Utility';
class UserApp extends React.Component{
    //does something with UserDataObj
    // also does somethign with utility
}

My question is, how many utility and UserDataObj instances will be created in memory, when UserApp is rendered. My guess is, it should be only 1 instance for both. But I want to confirm if importing n times creates a new instance every time.

Any good read on this topic is greatly appreciated.

Thanks

1 Answers

This depends on the bundling tool, and not React. I imagine that the new browser ES Module resolution scheme works in the same way.

Most bundlers that I know of, and other import schemes such as Node.js' require module resolution will cache the import between files and always return the same exported objetcs. This is a requirement for prototype inheritance, for example, otherwise, it would mess up the instanceof operator.

That exported new Utility() instance will be the same for any module that imports it. In order to generate new instances, you would have to have a function.

Related