npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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.

Readme

@nonnajs/react

React bindings for @nonnajs/di - a <NonnaProvider> context component plus useInjection()/useOptionalInjection()/useAllInjections()/useInjector() hooks, in the spirit of inversify-react.

License: MIT


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. Unlike inversify-react, there's no property-injection-onto-a-class-component story to bridge here - Nonna's own field injection (see the @nonnajs/di README) 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, matching injector.get(). If a token needs getAsync(), resolve it during your own bootstrap (before build() 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 a NonnaProvider with a differently-scoped child Injector if you need per-subtree isolation.

License

MIT © Manuel Santos