Table of contents
TogglePreface
Why would you want to share this technology?
Zustatnd itself is a relatively new technology compared to Redux, and it's also a front-end state management technology that my team is trying to implement at work. Through the actual implementation, I have some experience and ideas, and then I had the idea to write this article.
What are the problems with the existing structure?
Whether you use Redux or Context to handle state management, Zustand is more complicated than Zustand, and for engineers who join the project later, it will take time to understand it. The main goal of Zustand is to make front-end state management relatively simple and easy to understand, and this feature makes Zustand the choice of some companies.
About Condition Management
Before I introduce Zustand, what is "Condition Management"?
Currently, web pages are becoming more and more complex, and there is a difference between front-end and back-end, in which the front-end is more oriented to screen presentation, UI \ UX, user flow, different devices with or without a running version ... and so on.
The back-end is more of a functional implementation, including database management, login, registration...and so on.
Then for the front-end more and more complex, also began to have the concept of framework, and the current popular three major frameworks, respectively, React, Vue, Angular.
Different frameworks will also have different ways of "state management", for example:
React: basically, you just manage the data and render it from the "state".
Vue: "Two-way Binding" with Data and Components
Based on the React framework, it can be broadly categorized into
Local State
-
- useState
-
- useReducer
Context
-
- useContext
Third Party
-
- Redux
-
- Mobx
-
- Zustand
As you can see from this, just the "state management" in a React framework is already quite complex.
Therefore, this article will only focus on Zustand, and will also use real examples to introduce it.
We can also see how popular Redux, Mobx, and Zustand have been in the past year by comparing the total number of downloads of the packages below.
What's Zustand?
According to Zustand, it's a lightweight, fast, "state management" suite based on the Flux and Hook concepts.
p.s. The bear above is Zustand's iconic mascot!
Zustand is also designed to solve complex React state management problems such as Zombie Child Problem, React Concurrency, Context Loss, and so on.
If you want to know more about what these issues are, you can refer to the following links
Zombie Child Problem:React Redux Documentation
React Concurrency:Official React Documentation
React Context Loss:Stack Overflow
We can also find out about Zustand's ambitions to beat Redux through their official website.
Zustand Usage
The following two simple usages are for JavaScript users
Create your first Store
Zustand is built on Hooks, so the first store created is the one created by the Custom Hook, which can contain variables, objects, functions, etc. The first store created is the one created by the Custom Hook, which can contain variables, objects, and functions.And you can do the "state management" of the data through Set and Get.
import create from 'zustand' const useBearStore = create((set) => ({ bears: 0, increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), removeAllBears: () => set({ bears: 0 }), }))
Because it uses a Hook, it can be loaded directly into any component for use.
These states can also be rendered, which is a great boon in Zustand, as you can see that it can be done in just a few lines.
Here's a simple example of Zustand for TypeScript users.
function BearCounter() { const bears = useBearStore((state) => state.bears) return {bears} around here ...
} function Controls() { const increasePopulation = useBearStore((state) => state.increasePopulation) return
}
Zustand TypeScript Writer
In Zustand we will use create to create a new store.
Pass in the function, pass back the state via the Hook, and re-render it.
import create from "zustand" type Product = { sku: string; name: string; image: string } type CartState = { products: Product[] cart: { [sku: string]: number } addToCart: (sku: string) = > void removeFromCart: (sku: string) => void } // Selectors // ... // Initialize our store with initial values and actions to mutate the state export const useCart = create<CartState>(set => ({ products : [ // ... ], cart: {}, // Actions // ... }))
Here we also show how Redux and Mobx are written, so readers can compare the differences, but this article will not focus on Redux or Mobx, only on Zustand and its state management.
Redux TypeScript Writer
import { createSlice, configureStore, PayloadAction } from "@reduxjs/toolkit" import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux" // Slices // Definee the shape of the state and how to mutate it type ICart = { [ sku: string]: number } const cartInitialState: ICart = {} const cartSlice = createSlice({ name: "cart", initialState: cartInitialState, reducers: { // ... }, }) type IProduct = { sku: string; name: string; image: string } const productsInitialState: IProduct[] = [ // ... ] const productsSlice = createSlice({ name: "products", initialState: productsInitialState, reducers: {}, }) // Actions // ... // Selectors // ... // Store export const store = configureStore({ reducer: { cart: cartSlice.reducer, products: productsSlice.reducer, }, }) // ... const App = () => { return ( <Provider store={store}> <NavigationContainer> <Stack.Navigator>{/* ... */}</Stack.Navigator> <StatusBar style="auto" /> </NavigationContainer> < /Provider> ) }
Mobx TypeScript Writer
import { types, Instance } from "mobx-state-tree" const Product = types.model({ sku: types.string, name: types.string, image: types.string, }) // Model and type our data with mobx state tree const CartStore = types .model("CartStore", { products: types.array(Product), cart: types.map(types.number), }) // Actions to mutate the state .actions(store => ({ // ... })) // Views are like selectors .views(self => ({ // ... })) type CartStoreType = Instance<typeof CartStore> // Spin up a hook to use our store and provide initial values to it let _cartStore: CartStoreType export const useCart = () => { if (!_cartStore) { _cartStore = CartStore.create({ products: [ // ... ], cart: {}, }) } return _cartStore }
According to the Zustand official, the above points are listed and briefly explained here.
Redux
Redux itself is a more complex state management tool, there will be Actioins, View, and State processes.
The following is the official Redux data flow schematic, and you can see that the learning threshold is relatively high if you want to use Redux's state management tools from scratch.
Context
Context itself is categorized as state management, but it's actually more of a centralized way of triggering state.
Compared to Zustand, it's not easy to manage because it's spread out in various files.
Conclusion
Advantages of using this technology
With Zustand, you can break down the data and logic of complex business logic and model these things. In addition to increasing readability, it also makes it easier to write tests.
Tips
Zustand itself is a full of easy to learn state management tools, and their own use in the work product is relatively convenient, including the state for Set, Get or use in the components are relatively convenient, full recommended for readers who want to target React for state management.
Thank you for watching ~ If you have any questions or want to discuss any of the above, please feel free to leave a comment or send me a private message!
Quote
https://github.com/pmndrs/zustand
https://react-redux.js.org/api/hooks#stale-props-and-zombie-children
https://docs.pmnd.rs/zustand/getting-started/comparison
Other article references
Why do big companies use Nx ? Monorepo Tool 5 Minute Quick Build
Do you really know Monorepo? 5 minutes to learn about front-end mega-architecture.