An implementation of the service locator pattern for React 16.13+ using Hooks, Context API, and Inversify.
- Service containers defined via a
ServiceContainer
component that usesInversify
's Dependency Injection containers under the hood - Support for hierarchical DI using nested
ServiceContainer
s including the capability of overriding services - Support for stateful services with reactivity when extending
StatefulService
- Services are singleton-scoped by default, but transient is supported for
useClass
anduseFactory
- Excellent TypeScript support throughout
npm install react-service-locator reflect-metadata
Modify your tsconfig.json
to enable experimental decorators:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
Import reflect-metadata
in your app's entrypoint (for example index.tsx
):
import 'reflect-metadata';
Place a <ServiceContainer>
in the component tree:
import { ServiceContainer } from 'react-service-locator';
...
function App() {
return (
<ServiceContainer>
<SignInPage />
</ServiceContainer>
);
}
Define a service:
import { Service, Inject } from 'react-service-locator';
@Service()
export class SessionService {
// Dependency injection is handled by Inversify internally
@Inject(HttpService)
private readonly httpService;
public login = async (username: string, password: string): Promise<void> => {
await this.httpService.post('/login', { username, password });
};
}
Obtain the service:
import { useService } from 'react-service-locator';
...
export function SignInPage() {
// Service location is handled by Inversify internally
const sessionService = useService(SessionService);
return (
<button onClick={() => sessionService.login('john', 'hunter2')}>
Sign In
</button>
);
}
By default, all classes decorated with @Service
are automatically registered in the service container. The decorator receives two optional parameters: provide
and scope
. If not specified, provide
will be the target class and scope
will be singleton
:
@Service()
class HttpService {}
is equivalent to:
@Service({ provide: HttpService, scope: 'singleton' })
class HttpService {}
For more control, you can also register services on the <ServiceContainer>
:
function App() {
return (
<ServiceContainer
services={[
SessionService, // shorthand
{
// same as shorthand
provide: SessionService,
useClass: SessionService,
scope: 'singleton', // optional
},
{
provide: someSymbol, // token can be an object, string, or symbol
useFactory: (context) =>
new SessionService(context.container.get(ServiceB)),
scope: 'transient',
},
{
provide: 'tokenB',
useValue: someInstance,
},
]}
>
<Foo />
</ServiceContainer>
);
}
Note: Services registered on the
<ServiceContainer>
will override those registered with just the decorator if they have the same token.
All forms of service registration are singleton-scoped by default. useClass
and useFactory
forms support a scope
option that can be set to either singleton
or transient
. Shorthand and useValue
forms will always be singleton-scoped.
You can obtain the service instance by simply doing:
const service = useService(SessionService);
You can also explicitly specify the return type:
// service will be of type SessionService
const service = useService<SessionService>('tokenA');
You can use this hook to obtain a partial or transformed representation of the service instance:
const { fn } = useServiceSelector(SessionService, (service) => ({
fn: service.login,
}));
This hook is most useful with Stateful Services.
Stateful services are like normal services with the added functionality of being able to manage internal state and trigger re-renders when necessary. Let's modify our service and see how this works:
import { Service, Inject, StatefulService } from 'react-service-locator';
@Service()
export class SessionService extends StatefulService<{
displayName: string;
idle: boolean;
} | null> {
@Inject(HttpService)
private readonly httpService;
constructor() {
super(null); // initialize with super
}
// Can also initialize this way.
// constructor() {
// super();
// this.state = null;
// }
get upperCaseDisplayName() {
return this.state?.displayName?.toUpperCase();
}
public async login(username: string, password: string): Promise<void> {
const { displayName } = await this.httpService.post('/login', {
username,
password,
});
this.setState({
// value is type checked
displayName,
idle: false,
});
}
public setIdle(idle: boolean) {
this.setState({ idle }); // can be a partial value
}
}
When using useService
to obtain a stateful service instance, every time this.setState
is called within that service, useService
will trigger a re-render on any component where it is used.
We can avoid unnecessary re-renders by providing a second parameter (depsFn
) to useService
:
export function Header() {
const sessionService =
useService(SessionService, (service) => [service.state.displayName]);
...
}
Now, re-renders will only happen in the Header
component whenever state.displayName
changes in our service. Any other change to state will be ignored.
depsFn
receives the entire service instance so that you have more control. The function must return a dependencies list similar to what you provide to React's useEffect
and other built-in hooks. This dependencies list is shallow compared every time this.setState
is called.
Another way to obtain a stateful service besides useService
is with useServiceSelector
. This hook will behave the same way as when called with non stateful services, but additionally it will trigger a re-render whenever this.setState
is called and if and only if the result of selectorFn
has changed.
const { name } = useServiceSelector(SessionService, (service) => ({
name: service.state.displayName,
}));
If selectorFn
's result is a primitive value it will be compared with Object.is
. If it is either an object or array, a shallow comparison will be used.
You can provide an alternative compare function as an optional third parameter, if needed.
The main difference between useService
and useServiceSelector
is that the former will always return the entire service instance, while the latter will only return the exact result of its selectorFn
which can be anything. With useService
the depsFn
can define a set of dependencies for re-renders while still giving you access to everything the service exposes. This can be good in some cases, but it can potentially lead to situations where in your component you access some state that you forget to add to the dependency list which could result in stale UI elements.
With useServiceSelector
you are forced to add everything you need in your component to the selectorFn
result, so there's less room for mistake.
-
Service locator? Isn't this dependency injection?
Although they are very similar, there is a slight difference between the two. With the service locator pattern, your code is responsible for explicitly obtaining the service through a known mechanism or utility. In our case we are using the
useService
hook as our service locator.More answers to the difference between the two here.