# prev/state 로 상태관리하기 → 추후 immer 미들웨어 사용

import { create } from "zustand";
import { devtools } from "zustand/middleware";

const collectionStore = (set) => ({
  collection: {
    collectionName: "",
    key: 0
  },
  setCollection: (collectionName, key) =>
    set({
      collection: {
        collectionName,
        key,
      }
    }),
  collectionList: [],
  setCollectionList: (newCollection) =>
    set((prev) => ({
      collectionList: [...prev.collectionList, newCollection]
    })),
  deleteCollectionList: (index) => set((prev) => {
    const deletedCollectionList = [...prev.collectionList];

    deletedCollectionList.splice(index, 1);

    return {
      collectionList: deletedCollectionList
    };
  }),
});

const useCollectionStore = create(devtools(collectionStore));

export {
  useCollectionStore,
};

# zustand에서 웹 스토리지 사용하기

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

const collectionStore = persist(
  (set) => ({
    collection: {
      collectionName: "",
      key: 0,
    },
    setCollection: (collectionName, key) =>
      set({
        collection: {
          collectionName,
          key,
        }
      }),
    collectionList: [],
    setCollectionList: (newCollection) =>
      set((prev) => ({
        collectionList: [...prev.collectionList, newCollection]
      })),
    deleteCollectionList: (index) => set((prev) => {
      const deletedCollectionList = [...prev.collectionList];

      deletedCollectionList.splice(index, 1);

      return {
        collectionList: deletedCollectionList
      };
    }),
  }),
  {
    name: "collection-storage",
    storage: createJSONStorage(() => sessionStorage),
  }
);

const useCollectionStore = create(devtools(collectionStore));

export {
  useCollectionStore,
};

References

React 상태 관리 라이브러리 Zustand의 코드를 파헤쳐보자

Zustand Documentation