Injecting Hooks Into React Components
Dependency Injection is a design pattern providing dependencies to a function (or class) in call sites rather than importing them directly in the implementation. Using the pattern it is easier to supply different implementations for dependencies depending on the call site (e.g., modular code reuse, tests, and component explorer). A loosely coupled codebase can be more maintainable. Hooks are used for writing stateful React components without introducing a class. This post explores three ways how to inject hooks to React components instead of importing them:
- passing hooks in props
- currying hook parameters (component factories)
- react-facade, passing hook implementations through Context
Update 2023-03-31: Please check out the improved version of the article at Wolt Careers Engineering Blog, which discusses the topic more thoroughly.