zustand persist 사용하기

브리·2023년 10월 14일
1

zustand로 프로젝트를 진행하던 중 zustand로 관리하는 state를 localstoage에 저장해야할 일이 생겼다.
zustand 자체에서 제공하는 persist 기능이 있다기에 사용해보려고 한다. 일단은 시간이 없어 간단하게 작성하고 추후에 좀 더 정리할 예정

zustand git hub에 올라와있는 사용방법을 살펴보면 기존 create 함수 안에 persist로 감싸주는 방식으로 사용한다.

사용방법

export const useBoundStore = create(
  persist(
    (set, get) => ({
      // ...
    }),
    {
      // ...
      onRehydrateStorage: (state) => {
        console.log('hydration starts')

        // optional
        return (state, error) => {
          if (error) {
            console.log('an error happened during hydration', error)
          } else {
            console.log('hydration finished')
          }
        }
      },
    }
  )
)

해당 예시 코드에서는 set, get을 받아 get을 사용해주었으나 redux 나 기존 zustand의 습관이 남아있어서 나는 set만 넘기고 state로 구현해주었다.

option

사용할 수 있는 옵션은 많지만 기본적으로 필수적인 옵션은 한가지이다.

name(필수)

웹 스토리지의 key에 해당하는 이름으로 유니크한 이름 지정해주기

 {
      name: "cart-storage", //unique 한 이름
 },

storage (옵션)

default: localstorage

 {
      storage: createJSONStorage(() => sessionStorage
 },

using typescript

타입스크립트를 사용할 때 타입 제네릭을 기존처럼 create 뒤가 아닌 persist 뒤에 넣어준다.

type CartStateType = {
  ...
};

export const useCartStore = create(
  persist<CartStateType>(
    (set) => ({
     	...
    }),
    {
      name: "cart-storage",
    },
  ),
);
profile
무럭무럭

0개의 댓글