If you would like to follow along with the code example that I am using, you can find the source code on the GitHub repository created by me.
While this article covers the basics of Zustand, there's much more to explore and learn about this powerful state management library. To provide a comprehensive understanding, I will be breaking down Zustand into a series of small, easy-to-read articles. In this initial article, we'll focus on the fundamentals, and in future articles, we'll delve into more advanced concepts. So, stay tuned for upcoming content as we continue our exploration of Zustand's capabilities. Let's begin our journey into the world of Zustand!
Zustand, a lightweight and elegant state management library that revolutionizes the way we handle state in web applications. Zustand brings simplicity, flexibility, and performance optimizations to the forefront, empowering developers to tame the state management beast effortlessly.
Traditional state management approaches often involve convoluted techniques, intricate setups, and complex boilerplate code, leading to a higher cognitive load and reduced productivity.
Zustand serves as a compelling alternative to Redux. It shares many similarities with Redux, making it a familiar choice for developers. However, Zustand boasts a significantly smaller learning curve, making it easier to understand and integrate into applications, especially for those already familiar with Redux.
If you've previously worked with Redux, you're likely aware of the boilerplate code it requires. While Redux Toolkit and other libraries have emerged to reduce boilerplate, there is still a setup process involved, including creating reducers, defining action types, and wrapping the application with Redux's provider component. The setup process can be time-consuming and cumbersome, especially when compared to Zustand.
With Zustand, you'll find that the setup is minimal. All you need to do is create a store and access it directly in the components where you require state management, without the need for additional providers or complex wrapping. This simplicity not only saves development time but also enhances code readability and maintainability.
One of the standout advantages of Zustand is its flexibility. In Zustand, you can store a wide range of data types, including primitives, objects, and even functions. This flexibility allows you to handle complex state structures and enables the inclusion of asynchronous operations seamlessly. Unlike Redux, which requires middleware or additional libraries like Redux Thunk for handling asynchronous operations, Zustand provides a straightforward solution within its core functionality.
By leveraging Zustand, you can experience the benefits of a Redux-like state management approach while eliminating much of the boilerplate code and complexity. Zustand empowers you to focus more on your application's logic and functionality, rather than getting caught up in the intricate setup and configuration process of traditional state management libraries.
Because it offers
Whether you're starting a new project or looking to migrate from Redux, Zustand opens up a world of possibilities, enabling you to build robust and efficient applications with ease.
When it comes to render optimizations within your app, there are no major differences in approach between Zustand and Redux. In both libraries it is recommended that you manually apply render optimizations by using selectors.
Let's create a basic counter example to demonstrate the functionality of Zustand. To begin, we'll start by creating a store.
import { create } from "zustand";
const counterStore = create((set) => ({
counter: 0,
increment: () => set((state) => ({ counter: state.counter + 1 })),
decrement: () => set((state) => ({ counter: state.counter === 0 ? 0 : state.counter - 1 })),
reset: () => set({ counter: 0 }),
}));
export default counterStore;As you might have noticed, updating the state in Zustand requires using the set function provided by the library. This function shares conceptual similarities with the useState hook in React. In Zustand, direct mutation of the state is not allowed. Instead, we need to return a new state whenever we intend to update it.
It's important to note that the set function in Zustand merges state at a single level. If the state is not nested, there is no need to use the spread operator (...) because Zustand automatically handles the state merging process.
However, when dealing with nested objects, explicit merging becomes necessary. In such cases, you can utilize the spread operator pattern to achieve the desired state update. Here's an example:
import { create } from 'zustand'
const useCountStore = create((set) => ({
nested: { count: 0 },
increment: () =>
set((state) => ({
nested: { ...state.nested, count: state.nested.count + 1 },
})),
}))To disable the merging behavior, you can specify a replace boolean value for set like so:
set((state) => newState, true) // also called Replace FlagNow that the store is ready, you simply need to bind the store with the component. Unlike Redux, you don't require any providers to access the state. Here's how you can achieve this:
import useCounterStore from "./store";
export default function Homepage() {
const counter = useCounterStore((state) => state.counter);
const handleIncrement = useCounterStore((state) => state.increment);
const handleDecrement = useCounterStore((state) => state.decrement);
const handleReset = useCounterStore((state) => state.reset);
return (
<>
<h2 className="center">Counter Example</h2>
<div>
<p className="bold center">Counter Value: {counter}</p>
<div className="counter-actions">
<button onClick={handleIncrement}>Increment</button>
<button onClick={handleDecrement}>Decrement</button>
<button onClick={handleReset}>Reset</button>
</div>
</div>
</>
);
}You can optimize the code by creating individual components for specific functionalities such as the counter value, increment button, decrement button, and so on. In this basic example, if you have a deep component hierarchy, you can refactor the code to separate the subscriptions from Zustand, ensuring that it doesn't impact unnecessary re-renders. I'll discuss this optimization technique in more detail in future articles.
As you can see, accessing the state from the Zustand store doesn't require a heavy setup. Instead, you simply need to extract the specific pieces you need. It's important to only extract the necessary state in each component individually. Avoid doing something like this:
const yourStore = useStore();By extracting only the needed state from the store, you can keep your components lean and efficient, minimizing unnecessary re-renders and improving overall performance.
Remember, the goal is to access the required state in each component individually, keeping your codebase clean and ensuring that you only subscribe to the relevant data.
Some people recommend keeping actions within the same store to collocate state and actions together. However, personally, I prefer placing actions outside the store due to several advantages:
By separating actions from the store, you can achieve a cleaner and more modular codebase, making it easier to reason about your application's logic and ensuring better scalability.
Ultimately, the decision of whether to colocate actions within the store or keep them separate depends on your specific requirements and preferences. Both approaches have their merits, and it's essential to choose the one that aligns best with your project's architecture and development style.
import { create } from "zustand";
const counterStore = create(() => ({
counter: 0,
}));
const onIncrement = () => counterStore.setState((state) => ({ counter: state.counter + 1 }));
const onDecrement = () =>
counterStore.setState((state) => ({ counter: state.counter === 0 ? 0 : state.counter - 1 }));
const onReset = () => counterStore.setState({ counter: 0 });
export default counterStore;
export { onIncrement, onDecrement, onReset };import useCounterStore, { onIncrement, onDecrement, onReset } from "./store";
export default function ExternalStoreActionsPage() {
const counter = useCounterStore((state) => state.counter);
return (
<>
<h2 className="center">External Store Actions</h2>
<div>
<p className="bold center">Counter Value: {counter}</p>
<div className="counter-actions">
<button onClick={onIncrement}>Increment</button>
<button onClick={onDecrement}>Decrement</button>
<button onClick={onReset}>Reset</button>
</div>
</div>
</>
);
}As you can observe, there's no need to retrieve the action from the Zustand store or a hook. Instead, you can directly call the action from the store itself. This results in clean and concise code. Personally, I find this approach to be elegant and efficient. However, the choice of implementation ultimately depends on you and your team. It's essential to consider your project's requirements, coding style, and team preferences when deciding on the best approach for your application.
In Redux, if you want to perform asynchronous operations, you cannot directly execute them within the store. Instead, you need to employ additional techniques such as custom middleware or third-party solutions like Redux Thunk or similar libraries. However, in Zustand, you have the freedom to include almost anything in the store, including asynchronous operations. By updating the state using the set() function, you can seamlessly incorporate asynchronous functionality into your application without any additional dependencies. Zustand simplifies the process of managing async operations, providing a more streamlined and straightforward approach compared to Redux.
import { create } from "zustand";
const counterStore = create((set) => ({
counter: 0,
isLoading: false,
increment: async () => {
set({ isLoading: true });
await new Promise((resolve) => setTimeout(resolve, 2000));
set((state) => ({ counter: state.counter + 1 }));
set({ isLoading: false });
},
}));
export default counterStore;As you can see in the above code snippet, you can add async operation with the ease.
import useCounterStore from "./store";
export default function AsyncStorePage() {
const counter = useCounterStore((state) => state.counter);
const isLoading = useCounterStore((state) => state.isLoading);
const handleIncrement = useCounterStore((state) => state.increment);
return (
<>
<h2 className="center">Async Store</h2>
<div>
<p className="bold center">Counter Value: {counter}</p>
<div className="counter-actions">
<button onClick={handleIncrement} disabled={isLoading}>
{isLoading ? "Please wait ..." : "Increment"}
</button>
</div>
</div>
</>
);
}In conclusion, Zustand emerges as a powerful and elegant state management library that offers a refreshing alternative to traditional approaches like Redux. With its simplicity, minimal learning curve, and flexibility, Zustand empowers developers to efficiently manage state in their web applications.
Furthermore, Zustand's flexibility shines through in its ability to handle a wide range of data types, including primitives, objects, and even functions. The seamless integration of asynchronous operations within Zustand eliminates the need for additional middleware or external libraries, simplifying the development process.
With Zustand by your side, you can confidently navigate the complex landscape of state management and elevate your web development projects to new heights.