Using services in components
Three hooks resolve a service from the container in context. They accept the same things container.get() accepts (a class, a token, a bound token or a factory token) and differ in how they report loading and failure:
useServicereturns the state as an object.useSuspenseServicereturns the instance and suspends while it loads.useOptionalServiceisuseServicefor a token that may have no provider.
All three subscribe to the instance and resolve a new one when it is invalidated; see Scopes and invalidation. The examples use UserService from the DI quick start.
useService
data is the instance once it is ready and undefined before that. Narrow on data or isSuccess, not on isLoading alone: on the very first render of an instance that does not exist yet, nothing has started and every flag is false. isLoading turns true right after that render.
When the container already holds the instance, the first render returns it with isSuccess: true and the component never shows a loading state.
refetch() asks the container again. It returns the same instance unless that instance was destroyed in the meantime, so its use is retrying after an error. To get a new instance, invalidate the current one.
Suspense
useSuspenseService returns the instance directly. The component suspends while the service is built and throws to the nearest error boundary when it fails.
When the instance is invalidated the component suspends again, so the fallback is shown until the new instance is ready.
A failed resolution is remembered for that container, token and arguments. Resetting the error boundary or mounting the component again throws the same error without another attempt. Use useService and refetch() where a retry is needed.
Services that take arguments
A token with a schema takes arguments, and each distinct value of the arguments has its own instance. The hooks take the arguments as their second parameter, typed as the input of the schema.
Leaving the arguments out turns the hook's return type into an error string that names the missing keys ('Error: Your token requires args: userId'), so the first use of the result fails to compile.
All three hooks compare arguments by their JSON form, extended to Map, Set, RegExp and bigint, so an object literal written in the call needs no memoization. Pass plain data: two values that differ only in a function, or in the private state of a class instance, count as the same arguments.
When the arguments change, useService returns the previous instance for one render, then goes through isLoading to the new one. Render from the instance (profile.user) rather than from the prop when the two must agree.
One instance per item
Arguments are the simplest way to give each row of a list its own service: ProfileCard above already does it. Every component that passes the same arguments shares the instance, so a row and a toolbar acting on it see the same state.
These instances are singletons of the container: they stay alive after the row unmounts, until they are invalidated or the container is disposed. For state that should end with the component, use a scope.
Optional services
useOptionalService returns the same object as useService plus isNotFound. It is for a token that has a provider in some builds or configurations and none in others.
With no provider for ANALYTICS, isNotFound is true and error stays undefined. isNotFound is also set when the token has a provider but one of its dependencies has none. Any other failure is reported in error, including a class that is not decorated with @Injectable.
Errors
useService and useOptionalService put a failed resolution in error; useSuspenseService throws it. The value is the DIError the container rejected with. Branch on its code:
The codes a component usually meets are InitializationError, ProviderNotFound (no provider), TokenValidationError (the arguments failed the schema) and ScopeMismatchError (a request-scoped service used outside a ScopeProvider). The full list is in the DI API reference.
Outside render
In an event handler or an effect, take the container with useContainer and call it directly. It returns the scope when the component is inside a ScopeProvider and the root container otherwise.
Nothing is subscribed this way, which is what you want for a service that is only called, never rendered from.
Related: Scopes and invalidation, React API.