DjangoBoys DjangoBoys - 4 months ago 35x
AngularJS Question

React dependency injection or similar?

In Angular.js it is possible to use dependency injection. I did some browsing and was not able to find an implementation of it. Does React have something similar to that?


React has IoC, but not any concept of a DI container like Angular. That is, instead of having a container that knows how to create objects and passing in dependencies, you pass them explicitly by passing props to the component when you instantiate it (like <MyComponent items={this.state.items} />).

Passing dependencies as props isn't very common the React world though. Props are mostly used to pass data to components and not services/stores. But there's nothing stopping you from passing services/stores or even components as props (and certainly nothing wrong with it).

React has the concept of a context which is a shared object for a whole tree of components. So the top level component can say that the context for its subtree has an object containing something like a UserStore, a MessageStore, etc. A component further down in the component hierarchy can then say that it wants access to the UserStore in its context. By saying that, the UserStore is accessible to that component without having to explicitly pass it down from the top component to the bottom, and the component requesting it doesn't know how it was created/passed to it.

It has the benefit of a DI container where you have a central place for object creation which can be passed in further down. Here's a good intro to contexts:

Contexts are still an undocumented feature of React, which means that its API can change in any coming versions of React, so you might want to use it sparsely until it becomes documented.