zustand

模板代码

import { create,useStore } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";


type MainProps = {
  language: "zh" | "en";
  theme: "light" | "dark";
  direction: "ltr" | "rtl";
  count: number;
};
type SettingStore = {
  main: MainProps;
  // 使用 actions 命名空间来存放所有的 action
  actions: {
    setMain: (main: Partial<MainProps>) => void;
    resetMain: () => void;
  };
};
const initialState: MainProps = {
  language: "zh",
  theme: "light",
  direction: "ltr",
  count: 0,
};
const useSettingsStore = create<SettingStore>()(
  persist(
    (set) => ({
      main: initialState,
      actions: {
        setMain: (main) => {
          set((state) => ({ main: { ...state.main, ...main } }));
        },
        resetMain() {
          set({ main: initialState });
        },
      },
    }),
    {
      name: "settings-storage",
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => {
        const { language, theme } = state.main;
        return { main: { language, theme,count:0 } };
      },
    }
  )
);

export const useSettingsMain = () => useSettingsStore((state) => state.main);
export const useSettingActions = () => useSettingsStore((state) => state.actions);