DI container in React on top of React Context API #913
stalniy
started this conversation in
Contribution RFC
Replies: 1 comment
-
This is an interesting concept, the services provider would just import and expose on the context and it's easier to mock |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Summary
This proposal suggests to use DI container in React code. Instead of importing some service (e.g., axios) we need in a component, we should instead use
React.useContext
to use provided service instance.Motivation
Currently, code imports whatever service is needed in a component or hook. This leads to less testable code, what leads to absence of unit tests. By introducing single
React.Context
that provides all services at root level, we will be able to inject them at component level usinguseContext
hook. This allows us to create a simple DI container on top of React's Context APIExample
Without DI container
With DI container
<ServiceContainer value={}>
application context providerMain benefits
Beta Was this translation helpful? Give feedback.
All reactions