[React] redux-persist : storage에 redux상태 저장하기

GONI·2021년 10월 22일
1
post-thumbnail

별거 아니고 그냥 redux state를 storage에 저장할 때 사용하는 redux-persist에 대해 알아보자

세팅 방법

rootReducer.js파일에

import { persistReducer } from "redux-persist"
import storage from "redux-persist/lib/storage"

const persistConfig = {
  key: "root",
  storage,
  whiteList: ["cart"],
}

모듈을 불러오고 config설정을 해준다.
이 때 whiteList는 persist지정할 모듈을 말한다.

const rootReducer = combineReducers({
  user,
  cart,
  router: connectRouter(history),
})

export default persistReducer(persistConfig, rootReducer)

그 후 원래 내보내던 rootReducer를 persistReducer로 감싼다.
(요리강의 하는거같은건 기분탓)


그리고 redux사용을 위한 Provider설정 부분에

import { persistStore } from "redux-persist"
import { PersistGate } from "redux-persist/integration/react"

const persistor = persistStore(store)

<Provider store={store}>
  <PersistGate persistor={persistor}>
    <App />
  </PersistGate>
</Provider>,

또다시 모듈을 불러온 뒤 Provider안에 PersistGate로 감싸주면 redux-persist설정이 완료된다!


결과 화면

그렇게 모든 설정을 끝낸 뒤

아무리 새로고침을 해도 redux state는 저장되어 있다!
(간단하쥬?)

profile
오로지 나의 기억력을 위한 일지

1개의 댓글

comment-user-thumbnail
2023년 12월 22일

감사합니다. 도움 많이 되었어요!

답글 달기