@nonnajs/react
v3.0.0
Published
React bindings for @nonnajs/di - a <NonnaProvider> context component plus useInjection()/useOptionalInjection()/useAllInjections()/useInjector() hooks for zero-reflection dependency injection in React apps.
Maintainers
Readme
@nonnajs/react
React bindings for
@nonnajs/di- a<NonnaProvider>context component plususeInjection()/useOptionalInjection()/useAllInjections()/useInjector()hooks, in the spirit ofinversify-react.
Installation
# npm
npm install @nonnajs/react @nonnajs/di react react-dom
# Optional: Build-time AOT compiler
npm install --save-dev @nonnajs/compiler
# If using Vite in the browser
npm install --save-dev @nonnajs/vite-plugin@nonnajs/di and react are peer dependencies (React >=16.8, any @nonnajs/di 1.x).
Working Sample
A fully functional, runnable sample application is available on GitHub:
👉 nonnajs/sample-react (React 18 + Vite + @nonnajs/react)
Complete Example
1. Define Services
Services are standard TypeScript classes decorated with @Injectable() from @nonnajs/di.
// src/services/user.repository.ts
import {Injectable} from "@nonnajs/di";
export interface User {
id: string;
name: string;
email: string;
}
@Injectable()
export class UserRepository {
private readonly users: User[] = [
{id: "1", name: "Alice", email: "[email protected]"},
{id: "2", name: "Bob", email: "[email protected]"},
];
findAll(): User[] {
return this.users;
}
}// src/services/user.service.ts
import {Injectable} from "@nonnajs/di";
import {UserRepository, User} from "./user.repository";
@Injectable()
export class UserService {
// Constructor dependency is inferred automatically at build time with @nonnajs/compiler
constructor(private readonly userRepo: UserRepository) {}
getUsers(): User[] {
return this.userRepo.findAll();
}
}2. AOT Dependency Compilation (Optional, Recommended)
With @nonnajs/compiler, constructor dependencies are inferred at build time using TypeScript's TypeChecker with zero runtime reflection:
// package.json
{
"scripts": {
"prebuild": "nonna-compile",
"build": "tsc && vite build"
}
}Import the generated file once at application bootstrap:
// src/__generated__/nonna-dependencies.generated.ts (generated by `nonna-compile`)3. Application Bootstrap
Boot the container once at your app entry point, and make it available across your React tree via <NonnaProvider>:
// src/main.tsx
import React from "react";
import {createRoot} from "react-dom/client";
import {Nonna} from "@nonnajs/di";
import {NonnaProvider} from "@nonnajs/react";
import {App} from "./App";
// Import AOT-generated dependencies metadata (if using @nonnajs/compiler)
import "./__generated__/nonna-dependencies.generated";
async function bootstrap() {
// 1. Configure and build the container
const injector = await Nonna.injector().scan().build();
// 2. Render React tree wrapped with <NonnaProvider>
const root = createRoot(document.getElementById("root")!);
root.render(
<React.StrictMode>
<NonnaProvider injector={injector}>
<App />
</NonnaProvider>
</React.StrictMode>,
);
}
bootstrap();4. Component Injection with Hooks
Use useInjection(), useOptionalInjection(), useAllInjections(), or useInjector() inside any function component:
// src/components/UserList.tsx
import React from "react";
import {useInjection, useInjector} from "@nonnajs/react";
import {UserService} from "../services/user.service";
export function UserList() {
// Injects the singleton UserService instance from the nearest NonnaProvider
const userService = useInjection(UserService);
const users = userService.getUsers();
return (
<div>
<h2>User Directory</h2>
<ul>
{users.map(user => (
<li key={user.id}>
<strong>{user.name}</strong> ({user.email})
</li>
))}
</ul>
</div>
);
}Bundling For The Browser
@nonnajs/di uses Node.js AsyncLocalStorage by default for request scoping. When building for the browser with Vite, use @nonnajs/vite-plugin to automatically provide browser-safe shims:
// vite.config.ts
import {defineConfig} from "vite";
import react from "@vitejs/plugin-react";
import nonna from "@nonnajs/vite-plugin";
export default defineConfig({
plugins: [react(), nonna()],
});Why an already-built Injector?
NonnaProvider takes a ready Injector - never a builder, and never a Promise<Injector>. Bootstrapping (await Nonna.injector()...build()) is async, and belongs in your app's own entry point, before the first render - not something the provider does on your behalf. This keeps NonnaProvider itself trivial (a single Context.Provider, no implicit loading state, no suspense boundary you didn't ask for) and matches how inversify-react's <Provider container={container}> works: you own the container's lifecycle, the binding component just makes it available to the tree.
If you want a loading screen while the injector boots, render it yourself around the await:
async function bootstrap() {
const injector = await Nonna.injector().scan().build();
createRoot(document.getElementById("root")!).render(
<NonnaProvider injector={injector}>
<App />
</NonnaProvider>,
);
}
bootstrap();API
<NonnaProvider injector={injector}>
Makes injector available to every hook below it in the tree, via React context. Safe to nest (an inner NonnaProvider shadows an outer one, e.g. for a request-scoped sub-tree with its own child injector).
useInjector(): Injector
Returns the Injector from the nearest NonnaProvider. Throws if called outside one - every other hook here is built on top of this and inherits that behavior.
useInjection<T>(token: Token<T>): T
Resolves token via injector.get(token), memoized on [injector, token] so a transient-scoped token isn't reconstructed on every render. Throws exactly what Injector.get() throws (ProviderNotFoundError, AsyncProviderError, ScopeError, ...) - nothing is swallowed or converted.
const logger = useInjection(Logger);useOptionalInjection<T>(token: Token<T>): T | undefined
Like useInjection(), but resolves to undefined instead of throwing when token isn't registered - mirrors Injector.getOptional().
useAllInjections<T>(token: Token<T>): readonly T[]
Resolves every provider registered for token (for multi: true tokens) - mirrors Injector.getAll(). Resolves to [] if none are registered.
What this package deliberately doesn't do
- No class-component decorators /
connect()HOC. Unlikeinversify-react, there's no property-injection-onto-a-class-component story to bridge here - Nonna's own field injection (see the@nonnajs/diREADME) already covers "inject into a class", and React function components plus hooks are the idiomatic target for everything else. - No async resolution hook.
useInjection()is sync-only, matchinginjector.get(). If a token needsgetAsync(), resolve it during your own bootstrap (beforebuild()finishes, or via an eager provider) rather than inside a component. - No request-scope integration with the render tree.
Injector.runInScope()is designed around a request/call lifecycle (an HTTP request, a job run), not a component's render lifecycle - nest aNonnaProviderwith a differently-scoped childInjectorif you need per-subtree isolation.
License
MIT © Manuel Santos
