DEV Community

Cover image for When and Why you should do Dependency Injection in React

When and Why you should do Dependency Injection in React

Shadid Haque on November 07, 2019

Our React applications are composed of many small components or modules. The components that we write will sometimes be dependent on each other. As...
Collapse
 
jsardev profile image
Jakub Sarnowski

I have few remarks to your article:

The typical module system in JavaScript has a caching mechanism.

Typical module system in NodeJS, not JavaScript. This doesn't work that way on the browser.

What this means is that we can initialize our dependencies and it will be cached and we can inject it in multiple places without loading it again. We are creating a Singleton when we are exporting this module.

Even in NodeJS, this is not a best practice, as it can be easily broken. Check out this article.

And one more: I think it's not a good idea to use the Context API for injecting things like a websocket service. Context API is for passing data through the component tree, I guess that passing complicated objects out there might create problems (i.e. performance ones). For things like this - why not just import it?

Collapse
 
shadid12 profile image
Shadid Haque

Hey Jakub, that is a great feedback. Thank you for the input. I will do some more research on the module system. I have been injecting services like simple websockets and firebase real time DB instances through Context. And I totally agree if not careful these will lead to memory leaks. I will do some more research on these as well and definitely address these caveats. Good feedback though. Loved it :)

Collapse
 
sjbuysse profile image
sjbuysse • Edited

Would love to hear about the caveats & how to address them :)

Collapse
 
rooneyhoi profile image
Dax Truong

I would agree with Jakub comment that the Context API is better used for passing data. Also, have you consider using custom hook for reuse those thing?

Collapse
 
shadid12 profile image
Shadid Haque

This post is now quit old and yes custom hooks are a straight forward way to do this.