Skip to content

#frontend-architecture

Validating React Context Usage by Prop Drilling Opaque Tag Types

React context allows data to be passed to nested components outside props, reducing the need for prop drilling. Type checker can validate that a component passes correct values in a child component’s props. However, a component’s type signature does not expose the contexts it taps with useContext. Context-using hooks can be injected in props, making data access explicit and type-checkable. With dependency injection, type signatures in props are complete, allowing alternative implementations in different call sites, such as tests and component explorer configurations. If such customizability is unnecessary, it is enough to pass an opaque tag type that encodes which contexts are available, reducing some boilerplate code compared to dependency injection.

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.