Gathering detailed insights and metrics for react-service-locator
Gathering detailed insights and metrics for react-service-locator
npm install react-service-locator
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (98.27%)
JavaScript (1.61%)
Shell (0.12%)
Verify real, reachable, and deliverable emails with instant MX records, SMTP checks, and disposable email detection.
Total Downloads
31,147
Last Day
3
Last Week
25
Last Month
60
Last Year
3,224
MIT License
22 Stars
30 Commits
2 Forks
1 Watchers
1 Branches
1 Contributors
Updated on Feb 01, 2024
Minified
Minified + Gzipped
Latest Version
1.4.3
Package Id
react-service-locator@1.4.3
Unpacked Size
144.30 kB
Size
29.64 kB
File Count
60
NPM Version
8.4.1
Node Version
16.13.1
Cumulative downloads
Total Downloads
Last Day
50%
3
Compared to previous day
Last Week
47.1%
25
Compared to previous week
Last Month
-46.9%
60
Compared to previous month
Last Year
-77.2%
3,224
Compared to previous year
2
22
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
1npm install react-service-locator reflect-metadata
Modify your tsconfig.json
to enable experimental decorators:
1{ 2 "compilerOptions": { 3 "experimentalDecorators": true, 4 "emitDecoratorMetadata": true 5 } 6}
Import reflect-metadata
in your app's entrypoint (for example index.tsx
):
1import 'reflect-metadata';
Place a <ServiceContainer>
in the component tree:
1import { ServiceContainer } from 'react-service-locator'; 2... 3 4function App() { 5 return ( 6 <ServiceContainer> 7 <SignInPage /> 8 </ServiceContainer> 9 ); 10}
Define a service:
1import { Service, Inject } from 'react-service-locator'; 2 3@Service() 4export class SessionService { 5 // Dependency injection is handled by Inversify internally 6 @Inject(HttpService) 7 private readonly httpService; 8 9 public login = async (username: string, password: string): Promise<void> => { 10 await this.httpService.post('/login', { username, password }); 11 }; 12}
Obtain the service:
1import { useService } from 'react-service-locator'; 2... 3 4export function SignInPage() { 5 // Service location is handled by Inversify internally 6 const sessionService = useService(SessionService); 7 8 return ( 9 <button onClick={() => sessionService.login('john', 'hunter2')}> 10 Sign In 11 </button> 12 ); 13}
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
:
1@Service() 2class HttpService {}
is equivalent to:
1@Service({ provide: HttpService, scope: 'singleton' }) 2class HttpService {}
For more control, you can also register services on the <ServiceContainer>
:
1function App() { 2 return ( 3 <ServiceContainer 4 services={[ 5 SessionService, // shorthand 6 { 7 // same as shorthand 8 provide: SessionService, 9 useClass: SessionService, 10 scope: 'singleton', // optional 11 }, 12 { 13 provide: someSymbol, // token can be an object, string, or symbol 14 useFactory: (context) => 15 new SessionService(context.container.get(ServiceB)), 16 scope: 'transient', 17 }, 18 { 19 provide: 'tokenB', 20 useValue: someInstance, 21 }, 22 ]} 23 > 24 <Foo /> 25 </ServiceContainer> 26 ); 27}
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:
1const service = useService(SessionService);
You can also explicitly specify the return type:
1// service will be of type SessionService 2const service = useService<SessionService>('tokenA');
useServiceSelector
hookYou can use this hook to obtain a partial or transformed representation of the service instance:
1const { fn } = useServiceSelector(SessionService, (service) => ({ 2 fn: service.login, 3}));
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:
1import { Service, Inject, StatefulService } from 'react-service-locator'; 2 3@Service() 4export class SessionService extends StatefulService<{ 5 displayName: string; 6 idle: boolean; 7} | null> { 8 @Inject(HttpService) 9 private readonly httpService; 10 11 constructor() { 12 super(null); // initialize with super 13 } 14 15 // Can also initialize this way. 16 // constructor() { 17 // super(); 18 // this.state = null; 19 // } 20 21 get upperCaseDisplayName() { 22 return this.state?.displayName?.toUpperCase(); 23 } 24 25 public async login(username: string, password: string): Promise<void> { 26 const { displayName } = await this.httpService.post('/login', { 27 username, 28 password, 29 }); 30 this.setState({ 31 // value is type checked 32 displayName, 33 idle: false, 34 }); 35 } 36 37 public setIdle(idle: boolean) { 38 this.setState({ idle }); // can be a partial value 39 } 40}
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
:
1export function Header() { 2 const sessionService = 3 useService(SessionService, (service) => [service.state.displayName]); 4 ... 5}
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.
1const { name } = useServiceSelector(SessionService, (service) => ({ 2 name: service.state.displayName, 3}));
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.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no SAST tool detected
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
24 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-03-03
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More