What is Zustand? React Front End State Management

zustand
Zustand

 

Zustand mascot

Preface

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.

Zustand npm doanload

 

https://npmtrends.com/mobx-vs-react-redux-vs-zustand


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 }), }))
				
			
Binding of components

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) =&gt; state.bears) return <h1><span class="ez-toc-section" id="bears-around-here"></span>{bears} around here ...<span class="ez-toc-section-end"></span></h1>
} function Controls() { const increasePopulation = useBearStore((state) =&gt; state.increasePopulation) return <button onclick="{increasePopulation}">one up</button>
}

				
			

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 }
				
			

Can Zustand surpass Context and Redux?

 

https://github.com/pmndrs/zustand#why-zustand-over-redux

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.

Redux Data Flow

 

Redux Data Flow

Redux Data Flow and React Component Life Cycle
Almost everyone who wants to learn Redux had seen this image before. It’s pretty straight forward for me right now, but…dev.to

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.

Context Data Flow

 

Context Data Flow

[React] Context API
要在 React 中管理数据,您可以使用 Props、State 和 Context。在这篇博文中,我将介绍 Context 是什么...dev-yakuza.posstree.com


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.

Leave a Comment

Your email address will not be published. Required fields are marked *

en_USEnglish