Overview
Factory for creating type-safe Vue dependency injection contexts. Eliminates silent failures by throwing errors when context is not found, improving developer experience over rawprovide/inject.
Supports both static key mode (key fixed at creation) and dynamic key mode (key provided at runtime).
Signature
Parameters
Static injection key. When provided, the key is fixed at creation time.
Configuration object for dynamic key mode.
Optional suffix to append to the runtime key (e.g.,
'v0:panel' + ':item' → 'v0:panel:item')Default value to return when context is not found. Only valid in static key mode.
Return Value
A readonly tuple containing two functions:
Retrieves the context. In static mode, takes no arguments. In dynamic mode, requires a
key string.Throws an error if context is not found and no default value is provided.Provides the context to descendant components. In static mode, takes
context and optional app. In dynamic mode, also requires a key string.When app is provided, context is made available at application level. Otherwise, provided at component level.Returns the provided context value.Usage
Standalone Functions
You can also use the low-level functions directly:Error Handling
Unlike Vue’s nativeinject, useContext throws descriptive errors when context is missing:
Type Safety
Best Practices
Use Symbol keys for public APIs
Use Symbol keys for public APIs
Export InjectionKey symbols to prevent key collisions:
Choose the right mode
Choose the right mode
- Static key mode: Use for single, well-known contexts (theme, router, i18n)
- Dynamic key mode: Use when multiple instances need different keys (nested panels, list items)
- Suffix mode: Use when you need scoped variants of the same context type
Provide defaults sparingly
Provide defaults sparingly
Only provide default values when it’s safe for components to work without explicit provision. For required contexts, let the error throw to catch configuration mistakes early.
Related
createTrinity
Combine context with default instances
createPlugin
Create Vue plugins with context provision