乐闻世界logo
搜索文章和话题

How to create multiple instances of a Zustand store?

1个答案

1

When using Zustand for state management, it is common to create a single store to hold the application's state. However, in certain scenarios, we might need to create multiple instances of the same store logic, such as when managing state independently across different components or pages while maintaining identical state logic.

To create multiple instances of a Zustand store, we can implement the factory pattern. This involves creating a function that generates a new store instance each time it is called. Below, I will demonstrate how to implement this with an example.

First, we need to define a function to create the store:

javascript
import create from 'zustand'; // Define a factory function for the store const createStore = () => create(set => ({ count: 0, increase: () => set(state => ({ count: state.count + 1 })), decrease: () => set(state => ({ count: state.count - 1 })) })); // Use the factory function to create store instances const useStoreInstance1 = createStore(); const useStoreInstance2 = createStore();

In the above code, createStore is a factory function that creates a new, independent store instance each time it is called via the create function. useStoreInstance1 and useStoreInstance2 are two independent store instances created using this factory function, each maintaining its own state without interference.

This approach is particularly suitable for scenarios where the same logic needs to be used in multiple independent environments, such as different components or pages.

Application Scenario Example:

Suppose we have a large dashboard application where multiple components each require a counter, but their counts are independent of each other. We can create an independent store instance for each component, allowing them to maintain their own counter states without interference.

This method enhances code reusability and modularity while also making state management clearer and simpler.

2024年6月29日 12:07 回复

你的答案