zustand persist로 스토리지에 전역 상태 저장하기

이보경·2023년 11월 26일

https://github.com/pmndrs/zustand


zustand 기본 사용법

  1. useStore 훅 만들기
    : create 함수내에 상태와 상태를 변경하는 액션 함수들 작성
// store.tsx
import create from 'zustand';

// set 함수를 통해서만 상태를 변경할 수 있다
const useStore = create(set => ({
  bears: 0,
  increasePopulation: () => set(state => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 })
}));
  1. useStore 훅 사용하기
    : 셀렉터 함수를 전달
// 사용할 컴포넌트.tsx
// 상태를 꺼낼 때
function BearCounter() {
  const bears = useStore(state => state.bears);
  return <h1>{bears} around here ...</h1>;
}

// 액션을 꺼낼 때
function Controls() {
  const increasePopulation = useStore(state => state.increasePopulation);
  return <button onClick={increasePopulation}>one up</button>;
}

zustand persist

전역 상태를 사용하는데, 새로 고침 후에도 값을 사용하도록 스토리지에 값을 저장해야하는 경우 persist를 이용하면 된다.

https://github.com/pmndrs/zustand/blob/main/docs/integrations/persisting-store-data.md
"Persist 미들웨어를 사용하면 Zustand 상태를 저장소(예: localStorage, AsyncStorage, IndexedDB등)에 저장하여 해당 데이터를 유지할 수 있다."

  • create 함수 내에 persist(()=> (), { }) 형태로 작성
// 기본 사용 예시
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'

export const useBearStore = create(
  persist(
    (set, get) => ({
      bears: 0,
      addABear: () => set({ bears: get().bears + 1 }),
    }),
    {
      name: 'food-storage', // name of the item in the storage (must be unique)
      storage: createJSONStorage(() => sessionStorage), // (optional)이기 때문에 해당 줄을 적지 않으면 'localStorage'가 기본 저장소로 사용된다.
    },
  ),
)

읽어보면 좋을 자료

https://ui.toast.com/posts/ko_20210812

0개의 댓글