White(aegis4206)


ZuStand

同為狀態管理工具

套件安裝

npm i zustand 或 yarn add zustand

引入create創建Store

store.tsx
import { create } from "zustand";

const store = create((set, _) => {
    return ({
        // 初始化state值
        state: '',
        setState: (NewValue: string) => {
            // 回傳物件內使用內置函數set回傳狀態
            set((allState: any) => {
                return ({
                    // 在將全部狀態解構丟回物件
                    ...allState,
                    state: NewValue
                })
            })
        }
    })
})
    
export default store

ZuStand不需要額外使用Provider去包,可直接引入解構使用

component.tsx
import store from './store'

const { state, setState } = store();

另外若想使用Redux Devtools只需要在Store的set前多包一層devtools

store.tsx
import { devtools } from "zustand/middleware";

const store = 
    create(
        devtools(
            (set) => {
            ... ...
            }
        )
    )

非同步可直接async,不像Redux需額外透過thunk

Copyright © 2025 white.