Reactjs: Do classes/prototypes have any place in our applications?

Ad

An O.O Developer Making his Transition into a World of Modules

Almost all of my JavaScript coding experience has been in React and almost everything I've built strictly uses React Components,Stores, Actions and Dispatcher.

Outside of that, everything I try to abstract away I have placed into helper modules.(XUtils, YUtils WebAPIUtils, ect)


Where I got confused

But yesterday I ran into an issue that showed me a gap my understanding of React because I found myself wanting to create a helper class/prototype(however you like to encapsulate your code) to add to a component because the typical imported module would only have methods whereas I would need something that I could encapsulate variables.

It didn't feel right,but I can't explain why I feel like I can't plug in classes/prototypes into any part of my React code.

Question:

Should all of our helper classes to abstract away/delegate code be limited to modules? If so, can you explain a little bit of the philosophy behind why React programming is a world of modules?

Ad

Answer

Ad

the typical imported module would only have methods whereas I would need something that I could encapsulate variables

Modules can export anything. This is intentional.

export const someConstant = 4;
export class SomeClass {}
export function someFunction() {}

Want to keep a bunch of variables in a module so you can share them between a bunch of other modules? Sounds like a config file/store, go for it. This is a solid pattern.

Want to create a module with a factory function that returns class instances? Good idea, solid pattern.

Want to export a class from a module? This is what React recommends for its components. This pattern is explicitly encouraged by React, and is a good practice in general. Go for it.

Should all of our helper classes to abstract away/delegate code be limited to modules?

You can put anything in a module, export it, and import it into another module. This is a good practice to follow because it creates encapsulation and allows code reuse. But, should this code be limited to modules? That's a strange question.

  • Do you mean you want to abstract code without reusing it? I don't know what that looks like.
  • Do you mean you want to abstract code and share it without it being a module? How are you sharing it?

Abstracting code into a module that is used by the rest of your application isn't a limitation. Its a super-power.

can you explain a little bit of the philosophy behind why React programming is a world of modules?

Because programming is a world of modules. Modules give us code reuse (the DRY pattern), and encapsulation (a key feature of object-oriented programmning). Modules encourage testability by limiting the scope and surface area of code. Tested modules give developers confidence in their resuse. Modules are all upside.

Ad
source: stackoverflow.com
Ad