Dependency injection for React
in a single hook

Resolve any service from your container with one useInject() call. No providers wrapping your tree, no context boilerplate, no prop-drilling. Built on inversify-props and InversifyJS 8.

$ npm install inversify-hooks
npm version npm downloads license

React 16.8+ · TypeScript-first · ESM + CommonJS

Register once, inject anywhere

Register your services at the entry point, then pull them into any component with the hook.

main.tsx
import { createRoot } from 'react-dom/client';
import { container } from 'inversify-hooks';
import App from './App';
import { IUserService, UserService } from './services';

container.addSingleton<IUserService>(UserService);

createRoot(document.getElementById('root')!).render(<App />);
App.tsx
import { cid, useInject } from 'inversify-hooks';
import { IUserService } from './services';

export default function App() {
  const [userService] = useInject<IUserService>(cid.IUserService);

  return <h1>Hello, {userService.getName()}</h1>;
}

Services injecting services

Outside of components, use property injection — the ID is inferred from the property name.

order.service.ts
import { inject, injectable } from 'inversify-hooks';

@injectable()
export class OrderService implements IOrderService {
  @inject() private userService!: IUserService;

  placeOrder() {
    return this.userService.getName();
  }
}

Three lifetimes

addSingleton

One shared instance for the whole app. The most common choice for services.

addTransient

A fresh instance every time the dependency is resolved.

addRequest

One instance per request scope — shared within a single resolution tree.

Core API

useInject<T>(id)

React hook returning [T] — the resolved service instance.

container

Shared container — addSingleton(), addTransient(), addRequest().

cid

Auto-generated cache of IDs, e.g. cid.IUserService.

@injectable() / @inject()

Decorators for services and service-to-service injection.

mockSingleton / resetContainer()

Testing utilities — swap implementations, reset state between tests.

getContainer() / setContainer()

Access or replace the underlying InversifyJS container.

Get started

$ npm install inversify-hooks

Requires React 16.8+ and Node.js 20.19+ · MIT licensed