redux-persist 로 state 를 지켜내자!

hyunwoo Jin·2022년 8월 19일
1

사용하게된 이유

redux 를 사용하여 props 지옥에 빠져있던 카테고리 state 를 해결하였다.
하지만 해당 카테고리로 이동 후 새로고침이되면 state가 초기화(?) 여튼 날아가버려 페이지가 정상적으로 렌더링되지 않았다. 이를 해결하기 위해 구글링했고 redux-persist를 통해 해결할 수 있었다.

redux-persist

redux-persist 는 redux 에 저장된 state 들을 로컬 스토리지 혹은 세션 스토리지에 저장하여 새로고침 시에 사라지는 state 들에 대한 대응이 가능했다.

설치

npm install --save redux-persist

or

yarn add redux-persist

src/reducer.js

localStorage를 사용할 경우

import storage from 'redux-persist/lib/storage

session Storage를 사용할 경우

import storageSession from 'redux-persist/lib/storage/session
import { combineReducers } from "redux";
import categoryReducer from "./reducers/categoryReducer";
import detailReducer from "./reducers/detailReducer";import { persistReducer } from "redux-persist";import storage from "redux-persist/lib/storage";const persistConfig = {
  key: "root",
  // localStorage에 저장
  storage,
  // whitelist: 해당하는 리듀서만 스토리지를 사용한다.
  // blacklist: 해당하는 리듀서는 스토리지를 사용하지 않는다.
};
export const rootReducer = combineReducers({
  value: categoryReducer,
  detail: detailReducer,
});export default persistReducer(persistConfig, rootReducer);

src/index.js

import React from "react";
import ReactDOM from "react-dom/client";
import { Provider } from "react-redux";
import store from "./store";import { persistStore } from "redux-persist";import { PersistGate } from "redux-persist/integration/react";
import "./index.css";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));const persistor = persistStore(store);
root.render(
  <Provider store={store}><PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>
);

참고 페이지

profile
꾸준함과 전문성

0개의 댓글