react-service-injector
v1.0.0
Published
Hooks-based service injection for React
Downloads
24
Maintainers
Readme
React Service Injector
Hooks-based service injection for React.
Installation
First, install the required packages:
npm i react-service-injector
In the root of your application, wrap your app component in an InjectorProvider
:
import { Injector, InjectorProvider } from 'react-service-injector';
const injector = new Injector();
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
<React.StrictMode>
<InjectorProvider value={injector}>
<App />
</InjectorProvider>
</React.StrictMode>
);
That's it! You're now ready to start using the injector.
Usage
To define an injectable service, you can simply create a class:
export class CounterService {
public value = 0;
}
Then, to use this service in your components, use the useService
hook:
import { useService } from 'react-service-injector';
import { CounterService } from './CounterService';
export const CounterComponent = () => {
const counter = useService(CounterService);
return <div>{counter.value}</div>;
}
The injector will inject itself into the constructor of any class it instantiates. With this you can inject other services in a service class:
import { Injector } from 'react-service-injector';
import { CounterService } from './CounterService';
export class AnotherService {
private readonly counter: CounterService;
public constructor(injector: Injector) {
this.counter = injector.resolve(CounterService);
}
}
Manually Binding Services
Sometimes it may be necessary to create a manual binding for a service instance, rather than letting the Injector instantiate it. This can be especially useful when dealing with services from other packages.
import { Injector } from 'react-service-injector';
const injector = new Injector();
const fooInstance = new FooService('I am not injectable');
injector.bindTo(FooService, fooInstance);