
Research
Malicious npm Packages Impersonate Flashbots SDKs, Targeting Ethereum Wallet Credentials
Four npm packages disguised as cryptographic tools steal developer credentials and send them to attacker-controlled Telegram infrastructure.
react-service-locator
Advanced tools
React implementation of the service locator pattern using Hooks, Context API, and Inversify
An implementation of the service locator pattern for React 16.13+ using Hooks, Context API, and Inversify.
ServiceContainer
component that uses Inversify
's Dependency Injection containers under the hoodServiceContainer
s including the capability of overriding servicesStatefulService
useClass
and useFactory
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>
);
}
Service
decoratorBy 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.
useService
hookYou 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');
useServiceSelector
hookYou 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
}
}
useService
hookWhen 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.
useServiceSelector
hookAnother 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.
FAQs
React implementation of the service locator pattern using Hooks, Context API, and Inversify
The npm package react-service-locator receives a total of 5 weekly downloads. As such, react-service-locator popularity was classified as not popular.
We found that react-service-locator demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Four npm packages disguised as cryptographic tools steal developer credentials and send them to attacker-controlled Telegram infrastructure.
Security News
Ruby maintainers from Bundler and rbenv teams are building rv to bring Python uv's speed and unified tooling approach to Ruby development.
Security News
Following last week’s supply chain attack, Nx published findings on the GitHub Actions exploit and moved npm publishing to Trusted Publishers.