When is local state better than global state?
If state affects only the UI and behavior of a specific component, it should be local.
This is the main principle. Now let's break it down in detail.
When is local state better?
1) When the data is needed by only one component
Examples:
- form state (
email,password) - open/closed dropdown in a card
- the selected tab inside a component
- a local counter (
count) - input state (
value,isFocused)
Global state isn't needed here, it would only complicate the application.
2) When the state is temporary
For example:
- modal state (open/close)
- a temporary loading flag (
isLoading) - hover state (
isHovered) - the selected item in a list
This data lives only as long as the component is on screen.
3) When the state should not be shared
If every instance of the component must have its own copy of the data.
Example:
<TodoItem />
<TodoItem />
<TodoItem />Each item in the list must have its own state (open/closed, selected, edit mode).
If you make it global, the logic breaks.
4) When the state does not need to be "passed down" and "is not needed by others"
If the data does not overlap between components, keep it local.
5) When it's easy to manage via props/emit
Example:
<Modal :is-open="modalOpen" @close="modalOpen = false" />Why use a global store? The parent component is enough.
6) When global state complicates the architecture
Sometimes a store creates more problems than it solves:
- more code
- more dependencies
- harder to maintain
- harder to test
If the data is simple, there's no need to move it into Pinia.
When should you NOT move local state into global state?
If:
this state is used by no more than one component
it's UI state (modal, tabs, menu)
the component must have its own copy of the state
the data isn't needed when switching pages
there's no need to synchronize several components
A common mistake among juniors is "dragging everything into a global store". This makes the application complex and bloated.
Examples of specific situations
Good: local state
<script setup>
const isOpen = ref(false)
</script>
<template>
<button @click="isOpen = !isOpen">Toggle</button>
<p v-if="isOpen">Hello!</p>
</template>No one but this component needs it.
Bad: moving this into Pinia
This kind of state should not be made global, it's UI for local behavior.
Good: local form state
const email = ref('')
const password = ref('')
const errors = reactive({})There's no need to store this in a store, it's local logic.
Summary (short)
Local state is better than global when:
- it's needed by only one component
- the state is temporary
- the behavior relates to the UI
- each instance must have its own state
- props/emit is enough
- a global store would only complicate the code
Global is only for when the data is shared across many parts of the application.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.