Actions & State Mutations
Update your Zustand store with simple, synchronous, or asynchronous functions.
What are Zustand Actions?
In Zustand, 'actions' are simply functions that you define inside your store to modify the state. Because Zustand does not enforce strict reducers or dispatchers like Redux, you can write plain JavaScript functions.
You mutate the store's state using the set function provided by create.
Why is this better than Redux reducers?
Traditional Redux requires defining string constants (ADD_TODO), action creators, and a massive switch statement inside a reducer just to update a single value.
Zustand collapses all of that. You just write a function, call set, and you're done. The set function automatically performs a shallow merge on the top level of your state object, meaning you don't have to manually copy over unaffected properties.
Using the `set` function
The set function can be used in two ways:
1. **Passing an object** (when you don't care about the previous state): set({ count: 0 })
2. **Passing a callback** (when the next state depends on the previous state): set((state) => ({ count: state.count + 1 }))
Async actions are trivial. You just make your action function async, await your fetch call, and then call set when the data arrives. No extra middleware like redux-thunk is needed!
Store Mutations in Action
Use the top toolbar to interact with the Zustand store. Notice how clicking the actions triggers the set function and updates the state object predictably.
Zustand Store
Click the actions in the toolbar. Notice how the 'set' function updates the state effortlessly, without reducers or dispatchers.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Actions are plain functions defined alongside state in the store.
- The
setfunction automatically shallow-merges top-level state. - Use a callback
set((state) => ...)when relying on previous state. - Async actions work out-of-the-box with standard async/await.
Done with this concept?
Mark it complete to track your progress. No login needed.