Skip to main content

Local VS Global state

1. Local state (component state)

Local state is data that belongs to a specific component and is used only inside it.

Characteristics:

  • visible only inside the component
  • created through ref(), reactive(), or data()
  • each component instance has its own state
  • should not be used by other components
  • lives as long as the component lives

Example of local state

Counter.vue:

javascript
<script setup> import { ref } from 'vue' const count = ref(0) // local state </script> <template> <button @click="count++"> Count: {{ count }} </button> </template>

Here count exists only in this component.


2. Global state (shared state)

Global state is data that must be accessible to many components or the entire application.

Usually stored in:

  • Pinia (Vue 3 - the modern standard)
  • Vuex (legacy)
  • or through provide/inject (rarely)

Characteristics:

  • accessible from any component
  • stores important application data
  • exists as long as the application runs
  • convenient for synchronizing different parts of the UI

Example of global state (Pinia)

javascript
// stores/user.js import { defineStore } from 'pinia' export const useUserStore = defineStore('user', { state: () => ({ user: null, isLoggedIn: false }), })

Usage in a component:

javascript
<script setup> import { useUserStore } from '@/stores/user' const userStore = useUserStore() console.log(userStore.user) // accessible anywhere </script>

Local vs global - the main differences

CriterionLocal stateGlobal state
Where it's storedInside the componentIn a separate store (Pinia/Vuex)
ScopeComponent onlyThe entire application
LifecycleLives as long as the component livesLives as long as the application runs
What it's forUI logic, temporary dataAuthorization, cart, settings
AccessDirectly in the componentThrough the store
ReusabilityNoYes (any component can read/change it)

How do you know where to put state?

Local state - when:

  • a modal is open/closed
  • the active tab
  • an input's value
  • the state of a specific card
  • temporary flags (isLoading, isFocused)

Example: a like button - that's local a like counter for the whole profile - that's already global.


Global state - when:

  • is the user authenticated?
  • cart data
  • theme settings (light/dark)
  • a list of products used across different pages
  • an authorization token
  • favorites, settings, language

Global state is the data sources that matter to different parts of the application.


Summary (briefly)

Local state - data inside a component. Global state - shared application data, accessible to many components.

  • We create local state through ref()/reactive()
  • We create global state in Pinia/Vuex
  • Local state lives with the component
  • Global state lives the whole time

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.