如果有趣味理解更多用法及 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++}

比照其余状态治理框架

为什么是 zustand 而不是 redux?

  • 笨重灵便
  • 将 hooks 作为生产状态的次要伎俩
  • 不须要应用 context provider 包裹你的应用程序
  • 能够做到刹时更新(不引起组件渲染实现更新过程)

为什么是 zustand 而不是 react Context?

  • 不依赖 react 上下文,援用更加灵便
  • 当状态发生变化时 从新渲染的组件更少
  • 集中的、基于操作的状态治理

为什么是 zustand-vue 而不是 pinia?

  • 基于不可变状态进行更新, store 更新操作绝对更加可控
  • 将 composition api 作为生产状态的次要伎俩,而不是 Vue.use 全局注入

最重要的是

  • 基于 zustand-pub 能够为 Iframe、微前端、Module Fedetation、模块化、组件化 等业务场景,提供 跨利用、跨框架 的 状态治理 及 状态共享 能力。

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,  },};

更多生态及能力阐明