Course outline

Vue / Intermediate: feature state and effect ownership / Lesson 14

Provide, inject, and state ownership

Share a reactive dependency with descendants while keeping mutation and lifetime explicit.

About 19 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Provide and inject a reactive dependency.
  • Keep state mutations with the provider.
  • Test missing providers and independent instances.
  • Design provider scope, key identity and missing-dependency behavior for a Vue subtree.
  • Keep shared mutation and lifecycle ownership explicit across injected consumers.

Choose a dependency boundary

A distant descendant may need a value owned by an ancestor even though intermediate components do not use it. Provide and inject can pass that dependency through the component tree. Prefer explicit props and events for ordinary parent-child contracts; injection introduces an implicit dependency that must be documented and tested. Decide whether a missing provider is an error or has a meaningful default.

Provide owned state

The provider owns a count and exposes a readonly view together with an increment operation. Descendants can observe the reactive ref but request changes through the owner. This keeps the rules for mutation beside the state. The example uses a string key for clarity; shared Symbol keys are useful in larger systems to avoid accidental collisions.

vue Single-file component for a Vue project
<script setup>
import { provide, readonly, ref } from "vue";
import CounterButton from "./CounterButton.vue";
const count = ref(0);
function increment() { count.value += 1; }
provide("counter", { count: readonly(count), increment });
</script>
<template><section><CounterButton /></section></template>
Expected output
The child initially receives count 0.

The provider shares a readonly ref and its owned increment function with descendants.

Inject in a descendant

The child injects the dependency synchronously during setup and fails clearly if the required provider is absent. The injected ref remains connected to the provider; its top-level binding is unwrapped in the template. This example requires the provider and child in a Vue host. If a dependency is genuinely optional, specify an intentional default instead of masking a configuration mistake.

vue Single-file component for a Vue project
<script setup>
import { inject } from "vue";
const counter = inject("counter");
if (!counter) throw new Error("Counter provider is required");
const { count, increment } = counter;
</script>
<template><button @click="increment">Count: {{ count }}</button></template>
Expected output
Initially Count: 0; activating the button shows Count: 1.

The button reads the injected ref and requests an update through the provider function.

Define scope and lifetime

Injection resolves from the closest matching ancestor, so a nested provider can intentionally override an outer one. Each component provider can create its own state; an application-level provider has a wider lifetime. On a server, construct request-specific application and provider state rather than sharing private mutable values across requests. Document who creates, resets and disposes the dependency.

Verify the dependency contract

Mount a provider with two descendants and verify both observe an increment. Mount a second provider and confirm its count is independent, then test the required-provider failure. Check that consumers cannot directly mutate the readonly value and that the exposed operation enforces any domain rules. Test removal and remount when the provider owns external resources.

Choose a dependency boundary deliberately

provide and inject let an ancestor make a dependency available to descendants without passing it through every intermediate component. This is useful when a subtree shares a clear context, such as a reading-session selection or a formatting service. It does not remove ownership decisions: identify who creates the value, which descendants may consume it, how long it lives and what happens when it is unavailable. A direct prop and event may remain clearer for a short parent-child relationship.

A provider can be scoped to a component subtree or installed at the application level. A nested provider using the same key shadows an outer one for its descendants; a sibling outside that subtree still resolves the outer provider. Document that scope so a consumer does not unexpectedly receive a different session. The examples use Vue 3.5.44 and synthetic data; they require a configured Vue host and are not claimed executions.

Use stable keys and explicit fallbacks

The provider and consumer must use the same injection key. A shared Symbol exported from one module reduces accidental collisions compared with reusing a generic string in a large application. Two separately created Symbols with the same description are still different identities. Define the key once and import it from both sides. In TypeScript, an InjectionKey can describe the value shape, but a type alone does not create a runtime provider or validate external data.

Decide whether a dependency is required or optional. An optional consumer can supply a meaningful default; a required consumer can fail clearly when no provider exists. A default should not silently conceal a missing critical service or authorization decision. Test the missing-provider path and a nested override. Injection resolves dependencies within the component hierarchy, not from an arbitrary sibling or from a client-side security boundary.

Keep mutation with the owner

A provider can expose a ref and an action together. Descendants read the current value and request changes through the action, while the provider enforces rules such as a valid id or a maximum count. Exposing readonly state can communicate and enforce the intended mutation boundary for consumers. The action still needs validation where appropriate, and server operations still require server authorization. A readonly wrapper does not turn external data into trusted data.

Providing count.value passes the current primitive snapshot; providing the ref preserves its reactive relationship. Likewise, wrapping a property in computed or toRef can create an explicit live access path when the source changes. Document whether each consumer receives shared state or per-provider state. Two separate provider instances should not accidentally share a module-level mutable object merely because their setup code looks similar.

Match provider lifetime to the shared task

A provider created in a route subtree normally lives with that subtree. Removing the owner ends its local state and should release resources it owns; a later instance may start fresh. If state must survive navigation, place the owner at a longer-lived boundary or use an appropriate store, and define reset behavior. A nested provider can intentionally give one dialog its own selection while the outer page retains another.

In server rendering, avoid a module-level mutable singleton for user-specific context. A long-lived process may handle concurrent users, so create application and request-scoped owners according to the SSR integration and serialize only data the recipient may see. Client injection is a dependency mechanism, not a permission check. Test two synthetic requests and account changes at the actual server boundary if isolation is a requirement.

Verify scope, updates and missing dependencies

Mount a provider and consumer together in an isolated Vue test. Check the initial value, invoke the exposed action, wait for the Vue update and verify the descendant output. Add a nested provider with the same key and assert that inner and outer consumers see the intended distinct values. Test an absent provider and a fallback or clear failure according to the contract. A consumer-only test with a mock proves behavior under that mock, not the production provider’s lifetime.

For external subscriptions or async actions owned by a provider, test cleanup when its subtree ends and guard stale results. Verify that a consumer cannot bypass intended mutation rules through an exposed writable object. Test server authorization independently for protected work. Record the actual host and observations; the examples below are contextual fixtures and do not claim a browser or SSR execution.

20 worked examples

1. Provide and inject a value

Problem: Pass a reading label to a descendant.

  1. The provider and consumer use the same string key.
  2. The consumer is assumed to be inside the provider’s descendant subtree.
javascript Illustrative Vue 3.5.44 dependency-injection fixture.
// Ancestor setup
provide("readingLabel", "Notes")
// Descendant setup
const label = inject("readingLabel")

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: The descendant resolves Notes when the ancestor provides the matching key.

Why this result follows: Injection resolves a matching dependency from an ancestor context.

2. Nearest provider wins

Problem: Resolve a nested override for an inner consumer.

  1. Both providers use the same key in the stated tree.
  2. The inner provider is the nearest matching ancestor.
text Illustrative Vue 3.5.44 dependency-injection fixture.
Outer provides theme = "light"
Inner ancestor provides theme = "dark"
Consumer is inside Inner

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: The inner consumer receives dark for the matching theme key.

Why this result follows: A nested provider shadows the outer value for its own descendants.

3. Sibling outside override

Problem: Compare consumers inside and outside a nested provider.

  1. A has Inner as its nearest matching provider.
  2. B is not in Inner’s subtree and resolves Outer.
text Illustrative Vue 3.5.44 dependency-injection fixture.
Outer provides theme = "light"
Inner provides theme = "dark"
Consumer A inside Inner; consumer B outside Inner but inside Outer

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: A receives dark and B receives light.

Why this result follows: Provider scope follows the component ancestry of each consumer.

4. Provide a ref and action

Problem: Keep a counter update rule at its owner.

  1. The provider retains the writable ref.
  2. The exposed readonly view and action separate observation from mutation.
javascript Illustrative Vue 3.5.44 dependency-injection fixture.
const count = ref(0)
function increment() { count.value++ }
provide("counter", { count: readonly(count), increment })

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: A descendant can observe count and request an increment through the supplied action.

Why this result follows: The owner can enforce its update rule through the action.

5. Primitive snapshot versus ref

Problem: Choose what descendants should observe after a change.

  1. count.value is evaluated when provide receives the primitive.
  2. The live entry retains the ref wrapper.
javascript Illustrative Vue 3.5.44 dependency-injection fixture.
const count = ref(0)
provide("snapshot", count.value)
provide("live", count)
count.value = 1

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: A consumer of snapshot receives the provided number 0; a consumer of live can read the ref’s current value 1.

Why this result follows: A ref preserves a live reactive access path while a primitive is a snapshot.

6. Shared Symbol key

Problem: Use one exported key on both sides.

  1. Both sides import the same Symbol object.
  2. The provider is an ancestor in the stated context.
javascript Illustrative Vue 3.5.44 dependency-injection fixture.
// keys.js
export const sessionKey = Symbol("session")
// Provider: provide(sessionKey, session)
// Consumer: inject(sessionKey)

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: The consumer can resolve the supplied session when it is in the provider’s subtree.

Why this result follows: Matching key identity links the provider and consumer.

7. Different Symbol identities

Problem: Diagnose two keys with the same description.

  1. Symbol creates a distinct identity on each call.
  2. The description is a label, not the identity itself.
javascript Illustrative Vue 3.5.44 dependency-injection fixture.
const providerKey = Symbol("session")
const consumerKey = Symbol("session")
// providerKey === consumerKey is false

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: The separately created symbols do not match, so the consumer cannot resolve that provider using consumerKey.

Why this result follows: Injection keys must be the same value rather than merely having similar descriptions.

8. Optional fallback

Problem: Provide a useful default when no ancestor supplies a label.

  1. No ancestor supplies the requested key in the fixture.
  2. The second argument defines the fallback value.
javascript Illustrative Vue 3.5.44 dependency-injection fixture.
const label = inject("readingLabel", "Notes")
// No matching provider exists.

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: The consumer receives Notes as the fallback.

Why this result follows: An explicit default handles an optional dependency’s absence.

9. Required dependency

Problem: Fail clearly when a required context is missing.

  1. inject returns no supplied session in this fixture.
  2. The guard detects the missing required dependency.
javascript Illustrative Vue 3.5.44 dependency-injection fixture.
const session = inject(sessionKey)
if (!session) throw new Error("Reading session provider missing")

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: Without a matching provider, the consumer raises the specified error.

Why this result follows: A clear failure exposes a configuration error instead of silently using an unsafe default.

10. Application-level provide

Problem: Supply a service to an application’s descendants.

  1. The dependency is registered on this app before mounting.
  2. Consumers must use the same key and belong to this application context.
javascript Illustrative Vue 3.5.44 dependency-injection fixture.
const app = createApp(App)
app.provide(serviceKey, formattingService)
app.mount("#app")

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: Descendants of this application can inject formattingService with the matching key.

Why this result follows: Application-level provision defines a shared dependency boundary for that app.

11. Provider-owned validation

Problem: Reject an invalid selection through an action.

  1. The supplied id is absent from the allowed set.
  2. The early return prevents the assignment.
javascript Illustrative Vue 3.5.44 dependency-injection fixture.
function select(id) {
  if (!allowedIds.has(id)) return false
  selectedId.value = id
  return true
}
// allowedIds contains "n-1"; select("bad") returns false.

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: The invalid id is rejected and selectedId remains unchanged.

Why this result follows: A provider-owned action centralizes the update rule for descendants.

12. Readonly is not authorization

Problem: Assess a protected operation exposed through context.

  1. Readonly constrains client-side mutation through that view.
  2. It does not prevent a caller from making an independent request.
text Illustrative Vue 3.5.44 dependency-injection fixture.
Provider exposes readonly account state and a save action
Caller invokes save
Server authorization: still required

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: The server must authenticate and authorize the save regardless of the readonly client state.

Why this result follows: Client dependency boundaries do not replace server access control.

13. Live computed provision

Problem: Expose a derived label that follows source changes.

  1. The provided value is a computed ref rather than its current string.
  2. Its getter depends on count.value.
javascript Illustrative Vue 3.5.44 dependency-injection fixture.
const count = ref(1)
const label = computed(() => `${count.value} notes`)
provide("label", label)
count.value = 2

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: A descendant reading the injected computed ref sees 2 notes after the update.

Why this result follows: Providing the reactive wrapper preserves the derived relationship.

14. Separate provider instances

Problem: Keep two dialogs’ selections independent.

  1. Each provider instance creates its own state owner.
  2. Neither dialog uses a shared module-level selection in this fixture.
text Illustrative Vue 3.5.44 dependency-injection fixture.
Dialog A provider: selectedId = "a"
Dialog B provider: selectedId = "b"
Each dialog creates its own ref.

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: Consumers inside A see a and consumers inside B see b.

Why this result follows: Per-provider state follows the lifetime and scope of its own subtree.

15. Accidental shared singleton

Problem: Detect two providers wrapping the same mutable object.

  1. Both variables reference the same object.
  2. The mutation changes that shared object rather than an instance-local copy.
javascript Illustrative Vue 3.5.44 dependency-injection fixture.
const shared = { selectedId: "a" }
const providerA = shared
const providerB = shared
providerA.selectedId = "b"

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: providerB.selectedId is also b in this local model.

Why this result follows: Separate variable names do not create separate state owners.

16. Provider subtree removal

Problem: Trace local context when its owner is removed.

  1. The provider’s state is owned by the removed subtree.
  2. A later component instance is a new owner.
text Illustrative Vue 3.5.44 dependency-injection fixture.
Route subtree provides a local selection
Navigation removes the subtree
Later navigation creates a new provider instance

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: The old local provider ends; the new instance initializes according to its own setup contract.

Why this result follows: State lifetime follows its provider unless it is deliberately owned elsewhere.

17. Longer-lived shared owner

Problem: Preserve a selection across route changes deliberately.

  1. The current provider ends when its route subtree is removed.
  2. The required lifetime extends across both routes.
text Illustrative Vue 3.5.44 dependency-injection fixture.
Requirement: selection survives two sibling routes
Current provider: inside first route subtree

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: Move the owner to an appropriate common ancestor or shared store and define when it resets.

Why this result follows: Owner placement must cover the full required state lifetime.

18. SSR user isolation

Problem: Avoid sharing one injected user object across requests.

  1. A long-lived module can outlive an individual request.
  2. User-specific state must not be reused for another recipient.
text Illustrative Vue 3.5.44 dependency-injection fixture.
Request A user: Ada
Request B user: Basil
Risk: module-level mutable context reused by both

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: Create request-associated application and provider state, then verify concurrent response isolation.

Why this result follows: Request-scoped ownership prevents the modeled cross-user sharing.

19. Consumer-only mock limit

Problem: Interpret a test that injects a fake service.

  1. The fixture substitutes the dependency.
  2. The real provider’s scope and lifetime were not exercised.
text Illustrative Vue 3.5.44 dependency-injection fixture.
Consumer test: fake formatter returns "NOTES"
Production provider: not mounted

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: The test supports consumer behavior with the fake; it does not establish production provider wiring.

Why this result follows: A mock narrows the evidence to the contract represented by that mock.

20. Nested provider test

Problem: Verify outer and inner consumer scopes together.

  1. Consumer A lies outside the inner subtree and resolves the outer provider with value 1.
  2. Consumer B is inside the nested subtree and resolves the nearer provider with value 5.
text Illustrative Vue 3.5.44 dependency-injection fixture.
Outer provides count 1
Inner provides count 5
Consumer A outside Inner; consumer B inside Inner

This contextual example is not executed; a configured Vue component host is required where applicable.

Expected result: The planned integration test should observe A=1 and B=5.

Why this result follows: Testing both consumers confirms the intended shadowing boundary.

Common errors and fixes

A descendant receives no dependency.

Why it happens
The key or provider ancestry does not match.
How to fix it
Provide the same key above the consumer.
Prevent it next time
Test the required-provider failure explicitly.

A consumer changes shared state without enforcing its rules.

Why it happens
Writable state was exposed without an ownership contract.
How to fix it
Expose a readonly value and owner-controlled operations.
Prevent it next time
Document and test permitted transitions.

One request sees another user’s state.

Why it happens
Private mutable state is shared at server module scope.
How to fix it
Create request-scoped application and provider state.
Prevent it next time
Test two isolated synthetic requests.

20 practice exercises

1. What does a nested provider with the same key change?

Show hint

Trace each consumer’s component ancestry to the nearest matching key.

Show worked solution

A descendant resolves the nearest matching ancestor, so it receives the nested provider’s value. Test outer and inner consumers to confirm the intended scope.

A nested provider with the same key shadows the outer provider for its descendants. A consumer outside the nested subtree still resolves the outer value. Test both consumers so the intended scope is observable.

Check your solution

  • The inner consumer receives the nested value.
  • The outer sibling receives the outer value.

2. Why expose increment instead of a writable count?

Show hint

Separate observation from authority to change the source.

Show worked solution

The owner can enforce the update rules in one place while descendants observe the readonly value. This makes the shared contract easier to inspect and test.

Exposing a readonly count and an increment action keeps update rules in the provider while descendants observe the current value. The action can enforce validation in one place and makes the shared contract easier to test.

Check your solution

  • Consumers can observe the count.
  • Updates go through the owner’s action.

3. A page subtree needs one reading-session context across several descendants. Choose a boundary.

Show hint

The ancestor can own the shared context.

Show worked solution

Provide the session at a suitable ancestor and inject it in descendants that need it. Document its lifetime, missing-provider behavior and permitted updates rather than making it an implicit global.

Check your solution

  • The provider covers the intended subtree.
  • The context has an explicit owner.

4. A direct child needs one title and reports an edit. Is injection always necessary?

Show hint

Consider the shortest explicit contract.

Show worked solution

No. A prop and event can clearly express a direct parent-child relationship. Use provide and inject when the subtree dependency and scope justify avoiding intermediate prop forwarding.

Check your solution

  • The title flows as an input.
  • The child’s proposal has an explicit event.

5. Outer provides light and nested inner provides dark using the same key. What does each consumer see?

Show hint

Find the nearest matching ancestor.

Show worked solution

A consumer inside the inner subtree receives dark; a sibling outside it but under the outer provider receives light. Mount both in an integration test to verify the intended boundary.

Check your solution

  • The inner consumer sees dark.
  • The outer sibling sees light.

6. Two modules each create Symbol("session"). Will their injection keys match?

Show hint

Descriptions are not identity.

Show worked solution

No. Each Symbol call produces a different value even with the same description. Export one shared key and import it in both provider and consumer, then test resolution.

Check your solution

  • The separate symbols are unequal.
  • Both sides use the shared exported key.

7. A required injected service is absent. Choose an explicit failure behavior.

Show hint

Do not hide critical configuration errors.

Show worked solution

Detect the missing value and raise a clear error or use another documented required-dependency strategy. Test the missing-provider path rather than silently substituting an unsafe service.

Check your solution

  • The absence is detected.
  • The failure identifies the missing dependency.

8. An optional label has no provider. Supply a meaningful fallback.

Show hint

Use an explicit default.

Show worked solution

Inject the key with a default such as Notes when the contract permits an optional dependency. Test both the fallback and a supplied override so missing configuration is intentional.

Check your solution

  • The absent case yields Notes.
  • A provider can supply another label.

9. A provider shares count and descendants should not write it directly. Design the interface.

Show hint

Keep mutation at the owner.

Show worked solution

Provide a readonly view of count and an increment action that applies the owner’s rule. Test that descendants observe the updated count after invoking the action.

Check your solution

  • Consumers read the count.
  • The action is the intended update path.

10. A provider supplies count.value while count later changes from 0 to 1. What does the consumer have?

Show hint

The provided argument was a primitive.

Show worked solution

The consumer receives the number 0 as a snapshot. Provide the ref or another explicit reactive source when the descendant must observe later changes, and test the update.

Check your solution

  • The snapshot remains 0.
  • A provided ref reads the later value.

11. A provider shares a computed label based on count. How can it stay live?

Show hint

Provide the wrapper, not its current string.

Show worked solution

Provide the computed ref itself and let the consumer read it reactively. Change count and verify the descendant sees the new label after the Vue update.

Check your solution

  • The injected value remains a computed ref.
  • A count change updates the label.

12. A selection action receives an id outside the allowed set. Define the owner’s response.

Show hint

Validate before assignment.

Show worked solution

Reject the invalid id and leave the current selection unchanged, returning or displaying a useful result according to the contract. Test an allowed id and a rejected id separately.

Check your solution

  • The invalid id is rejected.
  • The previous selection remains.

13. Two dialog providers each create a local selection ref. Should their selections be shared?

Show hint

Each provider is an owner.

Show worked solution

No, not under this contract. Each dialog’s descendants resolve its own provider and changes in one dialog should not affect the other. Test both instances with distinct ids.

Check your solution

  • Dialog A retains its own selection.
  • Dialog B remains independent.

14. Two providers both reference one module-level mutable object. Explain the hidden sharing.

Show hint

Follow object identity.

Show worked solution

Both providers point at the same object, so a mutation through one is visible through the other. Create state per provider when isolation is required and test changes across both subtrees.

Check your solution

  • The shared reference is identified.
  • Independent providers receive distinct owners.

15. A provider is inside a route subtree but selection must survive route changes. What should change?

Show hint

The required lifetime is longer.

Show worked solution

Move the owner to a suitable common ancestor or shared store and define a reset policy. Test navigation between the relevant routes and ensure selection remains valid for the current account.

Check your solution

  • The owner outlives both routes.
  • Reset behavior is explicit.

16. A v-if removes a provider subtree. What happens to its local state?

Show hint

The owner instance ends.

Show worked solution

The removed provider’s local state ends with that component; a later new instance initializes its own state. If persistence is required, choose a longer-lived owner deliberately.

Check your solution

  • The old provider is removed.
  • A new provider follows its initialization contract.

17. A server reuses a module-level injected user object across requests. Identify the risk.

Show hint

A server process can outlive a request.

Show worked solution

One user’s mutation can affect another request. Create request-associated application and provider state, serialize only authorized data and test concurrent users plus an anonymous request.

Check your solution

  • User-specific state is request scoped.
  • Responses do not contain another user’s data.

18. A readonly injected account state is used to call save. Does it secure the API?

Show hint

Client mutation rules are not server authorization.

Show worked solution

No. The server must authenticate and authorize the operation independently, even if consumers cannot write the readonly client view. Test an unauthorized direct request.

Check your solution

  • The client action follows its local contract.
  • The server rejects unauthorized saves.

19. A consumer test injects a fake formatter. What remains unverified?

Show hint

The real provider was not exercised.

Show worked solution

Mount the production provider and consumer together to check key identity, scope and lifetime. Keep the fake-based test for the consumer’s behavior under the controlled formatter contract.

Check your solution

  • The fake test has a narrow claim.
  • Real provider wiring is tested separately.

20. A provider owns a subscription and async load. What should an integration test cover?

Show hint

The owner must clean up its work.

Show worked solution

Mount the provider subtree, observe registration, remove it and verify cleanup and stale-result protection. Test a late completion so an ended owner cannot update visible state.

Check your solution

  • The subscription is released.
  • A late result cannot publish after disposal.

Key takeaways

  • Injection follows the component ancestry.
  • Keep state changes with the provider.
  • Scope private server state to each request.
  • The nearest matching provider determines an injected value.
  • A provided ref remains live while a provided primitive is a snapshot.
  • Readonly state and actions can keep update rules at the owner.

Official references