Skip to main content
InterviewHubPRO
Section Overview
Q42

Question 42 of 50

Part 3: Advanced Internals, Scale & Production Architecture (Senior / Lead)

84%
Vue.js & Composition API (50 Qs)•Part 3: Advanced Internals, Scale & Production Architecture (Senior / Lead)

`provide` / `inject` vs Pinia: Patterns for Hierarchical Component Trees.

senior LevelCode ExampleComponentsState ManagementSystem Design

In Simple Words:

  • provide / inject: Dependency injection across parent-to-deep-child ancestor trees. Best for reusable component libraries (e.g. Tabs providing state to TabPanel) without coupling to global state.
  • Pinia: Global application state with devtools time-travel, plugins, actions, and cross-route persistence.
typescript
// InjectionKey pattern for type-safe DI in TypeScript
import { provide, inject, InjectionKey, Ref, ref } from 'vue';

interface ThemeContext {
  isDark: Ref<boolean>;
  toggleTheme: () => void;
}

export const ThemeKey: InjectionKey<ThemeContext> = Symbol('ThemeContext');

// In Parent / Provider:
const isDark = ref(true);
provide(ThemeKey, {
  isDark,
  toggleTheme: () => { isDark.value = !isDark.value; }
});

// In Deep Child:
const theme = inject(ThemeKey); // Type is inferred as ThemeContext | undefined