Mutation vs Action in Vuex: Key Differences and Usage
mutations are synchronous functions that directly change the state, while actions can be asynchronous and commit mutations to update the state. Use mutations for direct state changes and actions for async operations or complex logic before committing mutations.Quick Comparison
Here is a quick side-by-side comparison of mutations and actions in Vuex.
| Factor | Mutation | Action |
|---|---|---|
| Purpose | Directly change state | Perform async tasks and commit mutations |
| Synchronous or Asynchronous | Synchronous only | Can be asynchronous |
| How to call | Called by commit | Called by dispatch |
| Can modify state? | Yes, directly | No, commits mutations to modify state |
| Use case | Simple state updates | Async calls, complex logic before state change |
| Receives context? | Receives state and payload | Receives full context object |
Key Differences
Mutations are the only way to directly change the Vuex state. They must be synchronous to keep state changes predictable and trackable by Vuex's devtools. This means you cannot perform async operations inside mutations.
Actions are designed to handle asynchronous operations like API calls or timers. They do not directly mutate the state but instead commit mutations once async tasks complete. Actions receive a context object that gives access to commit, dispatch, and state, allowing more complex workflows.
In summary, use mutations for simple, direct state changes and actions when you need to perform async work or multiple mutations in sequence.
Code Comparison
This example shows a mutation that increments a counter in the state.
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; } } }); store.commit('increment'); console.log(store.state.count);
Action Equivalent
This example shows an action that waits 1 second before committing the same increment mutation.
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; } }, actions: { incrementAsync({ commit }) { setTimeout(() => { commit('increment'); }, 1000); } } }); store.dispatch('incrementAsync'); setTimeout(() => { console.log(store.state.count); }, 1100);
When to Use Which
Choose mutations when you need to make simple, synchronous changes to the Vuex state. They keep state updates clear and easy to track.
Choose actions when you need to perform asynchronous tasks like fetching data or when you want to run multiple mutations in a sequence. Actions help keep your state changes organized and maintainable when dealing with async logic.