Skip to content

Provide / Inject

provide and inject allow parent components to share data with deeply nested descendants without prop drilling.

Basic Usage

ts
// Parent component
import { provide, signal } from 'nexa-framework'

setup() {
  const theme = signal('dark')
  provide('theme', theme)
}
ts
// Any descendant component
import { inject } from 'nexa-framework'

setup() {
  const theme = inject('theme')
  // theme is the signal provided by the ancestor
}

Default Values

If no ancestor provides the key, inject returns the default value:

ts
const theme = inject('theme', signal('light'))

If no default is provided and the key is not found, inject returns undefined.

Using Symbols as Keys

For type safety and avoiding key collisions, use Symbol:

ts
// keys.ts
export const ThemeKey = Symbol('theme')

// Parent
provide(ThemeKey, signal('dark'))

// Child
const theme = inject(ThemeKey)

Common Patterns

App-Wide Configuration

ts
// Root component
setup() {
  provide('api-url', 'https://api.example.com')
  provide('locale', signal('en'))
}

Service Injection

ts
// Provide a service object
setup() {
  const auth = {
    user: signal(null),
    login: async (email, pass) => { /* ... */ },
    logout: () => { /* ... */ },
  }
  provide('auth', auth)
}

// Consume in any child
setup() {
  const auth = inject('auth')
  auth.login('user@example.com', 'password')
}

Limitations

  • provide and inject must be called inside a component's setup() function
  • Values are resolved from the nearest ancestor that provides the key
  • The current implementation walks the component's own provides object; parent chain resolution requires the parent to propagate its provides during component mounting

Released under the MIT License.