const useProfileStore = create((set) => ({ user: { name: 'Alice', details: { age: 25, city: 'New York' } }, // The Modern Way (Direct Mutation via Immer) updateCity: (newCity) => set((state) => { state.user.details.city = newCity; }), Hot Download 18 Looteri Jawani 2023 S01 Episo Site
const useBearStore = create((set) => ({ bears: 0, // Simple update function increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), // The "Direct Mutation" approach (Recommended for simplicity) removeAllBears: () => set((state) => { state.bears = 0 }), })); In the removeAllBears example above, we are assigning 0 to state.bears directly. This feels unnatural if you are used to Redux's immutability principles, but in Zustand, this is valid and encouraged. Every Zustand store is defined using a create function. The first argument of this function receives a set function. This set function is the engine behind every state update ( upd ). Www Desi Mallu Com 2021
// The Traditional Way (Spreading) updateCityOldSchool: (newCity) => set((state) => ({ user: { ...state.user, details: { ...state.user.details, city: newCity } } })) })); Notice how the "Modern Way" is significantly cleaner and less error-prone. Fetching data from an API and updating the store is a common requirement. Zustand makes this painless because the set function can be called anywhere, not just synchronously.
Here is a proper article on the subject. Zustand has emerged as one of the most beloved state management solutions in the React ecosystem. Praised for its minimal boilerplate and hook-based architecture, it simplifies how developers handle global state. However, understanding the nuances of how to update that state—specifically the upd (update) patterns—is crucial for writing performant and bug-free applications.
const useCounterStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), })); While Zustand makes updates easy, dealing with nested structures still requires care. If you are not using the direct mutation syntax, you must ensure you are copying nested structures correctly to prevent reference bugs.
import { create } from 'zustand';