Dependency Injection (DI) is a design pattern that allows us to eliminate hard-coding dependencies and make our applications loosely coupled, extendable, and maintainable. We can use Dependency Injection to make our application components reusable, maintainable, and testable.
React JS simplifies dependency management by using hierarchy-based, rather than module-based, dependency systems. A “higher-order” component takes a react component as an argument and eventually returns a react component.
There are several ways to do DI in ReactJS. Below is an example using a Higher-Order Component (HOC) and Context API.
1. Dependency Injection using Higher-Order Component(HOC):
Dependency.js
```
const injectProps = (Component, dependencies) => {
return class extends React.Component {
constructor(props) {
super(props);
this.dependencies = dependencies;
}
MyComponent.js
```
const MyComponent = ({myDependency}) => (…);
export default injectProps(MyComponent, {myDependency});
```
Looking at Dependency.js, we take a component and its dependencies as arguments. The component will then be wrapped in a higher-order component, where all props from dependencies are passed to the component we would like them to be injected into.
1. Dependency Injection using React Context
MyContext.js
```
import React from ‘react’;
const MyContext = React.createContext({});
export default MyContext;
```
App.js(parent component)
```
import MyContext from ‘./MyContext’;
const App = () => (
);
```
MyChildComponent.js
```
const MyChildComponent = () => {
return (
}
export default MyChildComponent;
```
In this example, the context is created using `React.createContext()`. The value passed to the Provider is given to any component that uses `MyContext.Consumer`. This allows us to inject values directly into deeply nested components without passing it through each layer. In this way, the value can be shared across multiple components.
It’s not conventional because react and redux use unidirectional data flow architecture. But it can be preferred to keep the components independent of each other.
In general, DI is not as embraced in React/Redux as it is in Angular because of the different philosophies and methodologies behind each of these separate frameworks.