3

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Just to clarify, any other script running in the same execution environment will share the same imported object. This will not work across browser pages, different machines, etc.
Thanks for the confirmation Marcus.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.