Dependency Injection in React — Part 3

Sergey Radzishevskii
2 min readJul 11, 2019

--

Dependency Injection part 1

Dependency Injection part 2

Ok finally we have a Dependency Injection container but we still need to figure out how we can inject dependencies built-in DI container to our react components.

React.Context is still our helper here.

  • we still need to add required contexts to make accustomed things work as before. We still wanna use connect and withApollo. But we could access state and apolloClient via our custom DIContext :).
  • We add our own DIContext. We will use it to read from DIContainer.

Injection into a component

As we discussed in part 1 we can inject properties into React components. We still need to write “with” HOC component but this time it will have our DI container and can get us whatever we need from it.

Ok it’s time to wrap

The resulted component will exclude IInjcetedPropsfrom IProps and will have only

interface IProps {
label: "string"
}
// and we can use it as
<HomePage label="foo" />

And what about testing

It’s a pure unit test. You don’t need to integrate any other dependency or Context at this moment. It works faster you test only what supposed to be tested.

Conclusion

Whatever solution you use, try to keep your React components simple. It’s a UI component it shouldn’t be complex, move logic away to sagas/services/backend.

--

--

Sergey Radzishevskii
Sergey Radzishevskii

Written by Sergey Radzishevskii

Enjoy turning complex systems into intelligible architectures chilling in my garden.

No responses yet