Redux-persist 사용법

shleecloud·2021년 11월 29일
0

들어가며

리액트 상태는 새로고침하면 전부 날라간다. 이를 유지하기 위해서는 localstorage 또는 sessionstorage를 사용해야 되는데 redux 환경에선 redux-persist라는 라이브러리가 이를 조작할 수 있다.

참고URL: kyounghwan01.github.io

persist store 정의

  • localStorage에 저장하고 싶으면 import storage from 'redux-persist/lib/storage
  • session Storage에 저장하고 싶으면 import storageSession from 'redux-persist/lib/storage/session

reducers/index.js

// reducers/index.js
import { combineReducers } from "redux";import { persistReducer } from "redux-persist";import storage from "redux-persist/lib/storage";const persistConfig = {
  key: "root",
  // localStorage에 저장합니다.
  storage,
  // auth, board, studio 3개의 reducer 중에 auth reducer만 localstorage에 저장합니다.
  whitelist: ["counter"]
  // blacklist -> 그것만 제외합니다
};

const rootReducer = combineReducers({
  auth,
  board,
  studio
});export default persistReducer(persistConfig, rootReducer);

src/index.js

// src/index.js

import React from "react";
import ReactDOM from "react-dom";
import { createStore, applyMiddleware, compose } from "redux";
import { Provider } from "react-redux";import { persistStore } from "redux-persist";import { PersistGate } from "redux-persist/integration/react";
import App from "./App";
import configureStore from "./store";

const store = createStore(rootReducer);const persistor = persistStore(store);

const Root = () => (
  <Provider store={store}><PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>
);

ReactDOM.render(<Root />, document.getElementById("root"));
profile
블로그 옮겼습니다. https://shlee.cloud

0개의 댓글

관련 채용 정보