Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
Export a class or an object instance difference

I am confused, or I can say, I have no clue how the exporting actually works.

I have a React app, and I have some protected Routes. On login, I create a Client object instance and pass it to child components through Context, and then consume it.

Recently I saw an approach where the example code exported an object instance from a file directly and just imported it in files they wanted to consume it.

/** My approach **/
export default Example

/** The Object Instance approach **/
export default new Example()

What is the lifecycle of the object instance? Are there any disadvantages with the second approach, because it seems way easier?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you export the class, with

export default Example

then consumers of the module will be able to instantiate their own instances, and each instance will be able to have its own data. For example

// 1.js
import TheClass from './TheClass';
const tc1 = new TheClass();
tc1.foo = 'foo';
// 2.js
import TheClass from './TheClass';
const tc2 = new TheClass();
tc2.foo = 'bar';

Both modules can continue to use tc1 and tc2 completely independently, since they're separate instances.

But if the original module exports an instance rather than a class, then all consumers of the module are forced to use the same instance:

// 1.js
import theInstance from '...';
theInstance.foo = 'foo';
// 2.js
import theInstance from '...';
// might not be a good idea to do theInstance.foo = 'bar' here
// because that will affect 1.js as well
// and will affect any other modules that imported the instance

In short - exporting the class is more reusable than exporting the instance. Sometimes potential reusability is something a script-writer will consider important, and sometimes it isn't. (And sometimes, even if you don't consider it useful initially, you may encounter a situation later that forces you to reconsider.)

And sometimes you want to make sure that there's only one instance ever in a script, in which case

export default new Example()

is a way to accomplish it.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!