Guides
Using in React

Use in React

redi provides API to help use DI in React.

Component provides dependencies

Component could connect with an array of dependencies. As a result, the connected component would create a RediContext to provide an injector.

const App = connectDependencies(
  function AppImpl() {
    //...
  },
  [[PlatformService]]
)

Component could also be connected to an injector.

const injector = new Injector([[PlatformService]])
 
const App = connectInjector(function AppImpl() {
  //...
}, injector)

The difference between connectDependencies and connectInjector is: connectDependencies would always create a new injector when the connected components mounts. However, connectInjector would never create an injector but use the created injector.

When two components that are connected to dependencies become ancestor and child components, the injectors would become parent child injector as well.

Component consumes dependencies

Use the following Hooks to get an injector or a dependency:

function Dashboard() {
  const injector = useInjector()
  const platformService = useDependency(PlatformService)
}

Use WithDependency to get dependency in class components:

class Dashboard extends React.Component {
  static contextType = RediContext
 
  @WithDependency(PlatformService)
  private readonly platformSrv!: PlatformService
}