【状态管理】zustand 中文文档,它来了!!!

文章介绍了在React应用中,由于Context的全量重渲染问题,推荐使用zustand作为状态管理库。zustand遵循React的不可变更新原则,避免了像MobX那样直接修改状态,提供了更好的性能和简洁的API。安装和使用步骤也在React和Vue环境中分别给出。

如果有兴趣了解更多用法及 api ,点击此处解锁中文文档

前言

是不是觉得 Redux 很难用?想用 Context 代替,但是你知道吗,Context 也有个很大的缺点:

  • context value发生变化时,所有用到这个context的组件都会被重新渲染,即使 component 需要的 state 可能根本沒有变动。基于 context 维护的模块越多,影响范围越大, 某些情况下会导致页面明显卡顿。
  • 另外,它依赖 Context Provider 包裹你的应用程序。

那么试试 zustand 吧,当然你可以选择 mobx,
zustand 与 mobx 最大的差别在于:

  • zustand 的状态更新遵循 react 思想,采用自然不可变更新, 而 mobx 类似 vue,基于数据劫持直接修改状态本身。
  • 体现在开发层面最直观的差异就是:
    • zustand 状态更新,新状态覆盖旧状态
    state = {a: 1}
    
    update(){
      stae = {a: 2} 
    }
    
    • mobx 状态更新,直接修改属性值
    state = {a: 1}
    
    update(){
      stae.a++
    }
    

React 三部曲

Step 1: 安装

npm install zustand # or yarn add zustand

Step 2: Store 初始化

创建的 store 是一个 hook,你可以放任何东西到里面:基础变量,对象、函数,状态必须不可改变地更新,set 函数合并状态以实现状态更新。

import { create } from 'zustand'

const useBearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

Step 3: Store 绑定组件,就完成了!

可以在任何地方使用钩子,不需要提供 provider
基于 selector 获取您的目标状态,组件将在状态更改时重新渲染。

选择目标状态:bears
function BearCounter() {
  const bears = useBearStore((state) => state.bears)
  return <h1>{bears} around here ...</h1>
}
更新目标状态:bears
function Controls() {
  const increasePopulation = useBearStore((state) => state.increasePopulation)
  return <button onClick={increasePopulation}>one up</button>
}

Vue 三部曲

什么,你还想试试在 Vue 中使用?那么 Step1 与 Step2 基本一致,不同的是 Step3 (Store 绑定组件):

Step 1: 安装

npm install zustand-vue # or yarn add zustand-vue

Step 2: Store 初始化

创建的 store 是一个 hook,你可以放任何东西到里面:基础变量,对象、函数,状态必须不可改变地更新,set 函数合并状态以实现状态更新。

import create from "zustand-vue";

const useBearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

export default useBearStore

Step 3: Store 绑定组件,就完成了!

基于 selector 获取您的目标状态,组件将在状态更改时重新渲染。

Store 绑定组件在 vue3vue2 中有所不同。

<template>
  <div>store.bears: {{ bears }}</div>
  <button @click="increasePopulation">increasePopulation</button>
  <button @click="removeAllBears">removeAllBears</button>
</template>

<script>
import useBearStore from "./store";

const increasePopulation = useBearStore((state) => state.increasePopulation);
const removeAllBears = useBearStore((state) => state.removeAllBears);

export default {
  data() {
    return {
      store: useBearStore(),
      bears: useBearStore((state) => state.bears),
    };
  },
  methods: {
    increasePopulation,
    removeAllBears,
  },
};
Redux、MobX 和 Zustand 三种状态管理工具在多个方面存在区别: - **学习曲线**:Redux 的学习曲线陡峭,因为其有严格的单向数据流和一系列概念,如 action、reducer 等;MobX 学习曲线中等;Zustand 学习曲线平缓,使用起来相对简单,DX 比 Redux 更好 [^1][^2][^3]。 - **代码量**:Redux 代码量较多,有大量模板代码,比如在 Redux 中甚至要先建立 dispatcher 的 instance,还要 import action 才能使用;MobX 代码量中等;Zustand 代码量极少 [^2][^3]。 - **异步处理**:Redux 需要中间件来处理异步操作;MobX 原生支持异步处理;Zustand 也原生支持异步处理 [^3]。 - **调试体验**:Redux 调试体验优秀,具备时间旅行调试功能;MobX 调试体验良好,有可观测性;Zustand 调试体验一般 [^3]。 - **适用场景**:Redux 适用于大型复杂应用,能让应用的数据流更加清晰,保证状态管理的规范性;MobX 适用于高频交互应用;Zustand 适用于中小型应用 [^1][^3]。 - **TypeScript 支持**:ReduxZustand 对 TypeScript 支持优秀;MobX 对 TypeScript 支持良好 [^3]。 ```python # 这里只是简单用代码示例展示对比的框架,无实际逻辑 # Redux 示例伪代码 import { createStore } from 'redux'; const initialState = { count: 0 }; function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; default: return state; } } const store = createStore(reducer); # MobX 示例伪代码 import { makeObservable, observable, action } from 'mobx'; class Counter { count = 0; constructor() { makeObservable(this, { count: observable, increment: action }); } increment() { this.count++; } } const counter = new Counter(); # Zustand 示例伪代码 import create from 'zustand'; const useStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })) })); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值