Dependency Injection
Last updated
Was this helpful?
Last updated
Was this helpful?
In React the need of is easily visible. Let's consider the following application tree:
The string "React Dependency Injection" should somehow reach the Title component. The direct way of doing this is to pass it from App to Header and then Header to pass it to Title. However, this may work for these three components but what happens if there are multiple properties and deeper nesting. Lots of components will have to mention properties that they are not interested in. It is clear that most React components receive their dependencies via props but the question is how these dependencies reach that point.
One way to achieve dependency injection is by using higher-order component to inject data.
The title is hidden in a middle layer (higher-order component) where we pass it as a prop to the original Title component. That's all nice but it solves only half of the problem. Now we don't have to pass the title down the tree but how this data will reach the enhance.jsx helper.
React has the concept of context. The context is something that every component may have access to. It's something like an event bus but for data. A single model which we can access from everywhere.
a place where we'll define the context
A place where we need data