Skip to main content

How does a component's local state differ from global state?

In short:

  • Local state → belongs to a specific component, used only inside it.
  • Global state → stored in the app's center (a store) and used by many components.

A component's local state

This is data that belongs only to one component.

For example:

js
data() { return { isOpen: false, searchQuery: '', form: { name: '', email: '' } } }

Or in the Composition API:

js
const isOpen = ref(false)

Characteristics of local state:

  • available only inside the component
  • created inside the component
  • the component manages it itself
  • destroyed when the component is removed
  • should not be used anywhere else
  • does not affect the application's logic

Examples of local state:

  • a modal's state (open/closed)
  • the search text in an input
  • a form's state
  • the selected tab in the current component
  • local flags (loading, error)

Global state

This is data that is needed by several components or the whole application. It is usually stored in a state manager:

  • Vuex
  • Pinia

Or via provide/inject.

Examples of global state:

  • the current user
  • the auth token
  • the shopping cart
  • a list of products loaded once
  • application settings (theme, language)
  • notifications
  • the state of a menu/sidebar
  • web socket data

Characteristics of global state:

  • available to all components
  • stored outside the component (a store)
  • exists for the entire lifetime of the application
  • used across several modules
  • changed centrally
  • affects the whole application's behavior

Examples of the difference (intuitively)

Example 1: shopping cart

  • Local state: whether the "Cart" modal is open
  • Global state: the list of items in the cart

Example 2: profile form

  • Local state: the current content of the inputs
  • Global state: the user's information

Example 3: themes (light/dark)

  • Local: which button is pressed in the component
  • Global: the application's current theme

How do you know whether state should go in the store?

Ask one question:

"Is this state needed by more than one component?"

  • YES → global state (store)
  • NO → local

Short Answer

Interview ready
Premium

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