Skip to main content

React Component Injection

@brushy/di supports component injection: register UI by token on the same Container used for services, then resolve with useInjectComponent in your shell (themes, white-label, A/B).

Tokens: Symbol only (never strings)

Use createToken("…") or Symbol("…"). Never use plain strings. At runtime, createToken returns Symbol(description); each token is unique and avoids collisions between modules or libraries.
Prefer createToken over raw Symbol so container.register and useInjectComponent infer types from the registered component. Register React components like any other provider with useValue on the container. No separate registration API is required.

Declarative bootstrap

Imperative registration

container.register returns a typed token. Props flow to useInjectComponent without extra generics:
Equivalent form:

Type inference (no manual generics required)

You do not need createToken<React.ComponentType<ButtonProps>>("BUTTON") in most cases. When you register with useValue, TypeScript infers the component type from the implementation. This is the same pattern used in @brushy/di-react tests:
Add explicit token generics only when you need a contract before the implementation exists (e.g. shared tokens.ts consumed by multiple theme packages).

useInjectComponent

Resolves a component from the nearest BrushyDIProvider container.

Import

With fallback

If the token is missing and no fallback is passed, dev builds show an error UI (web DOM by default). On React Native, call setInjectComponentErrorRenderer once at bootstrap. See Getting Started.

Optional helpers

These wrap container.register. Prefer the container API above for consistency with the rest of your DI graph.

Complete example: extensible UI shell

To swap a theme, replace component imports in providers or container.import a child container. See Best Practices.

Server Components

  • Register components on the container during bootstrap (server or client).
  • useInjectComponent runs in Client Components; pair with @brushy/di/core on the server for services.