Zustand provides two ways to update state inside the store:
- Use this when your update depends on the previous state.
- It ensures that you always modify the latest state.
set((state) => ({ count: state.count + 1 }));Why? The function receives
state, so we can safely modifycountbased on the latest state.
- Use this when updating state without depending on the previous state.
set({ user: newUser });Why? We don’t need the previous state here, just replacing
user.
- When returning an object in an arrow function, wrap it in
()to avoid JavaScript confusion.
✅ Correct:
set((state) => ({ count: state.count + 1 })); // ✅ Parentheses required❌ Incorrect (No return, JavaScript thinks {} is a function block)
set((state) => { count: state.count + 1 }); // ❌ Syntax error!If using a function block {}, explicitly use return:
set((state) => {
return { count: state.count + 1 };
});| Approach | When to Use? | Example |
|---|---|---|
set((state) => ({ ... })) |
If updating based on previous state | set((state) => ({ count: state.count + 1 })) |
set({ ... }) |
If replacing state without needing the old state | set({ user: newUser }) |
- If an arrow function uses
{}, it’s treated as a function block and requires an explicitreturn. - If it’s one line returning an object, wrap it in
().
✅ With {} (Needs return)
set((theme) => {
const toggle = theme.isDarkmode === "dark" ? "light" : "dark";
localStorage.setItem("theme", toggle);
return { isDarkmode: toggle }; // ✅ Explicit return needed
});✅ With () (Implicit Return)
set((state) => ({ count: state.count + 1 })); // ✅ No `return` needed- Use
set((state) => ({ ... }))when updating based on previous state, andset({ ... })when setting a new value directly. - Use
()around objects when using an implicit return in arrow functions. - If using
{}, you must usereturn.
🚀 Now you have a complete reference for Zustand state updates!