티스토리 뷰

기록/개인

엄청짧음) redux-persist

als982001 2023. 3. 26. 21:56

 redux를 이용하는데 새로고침을 하면 state가 계속 날아가서 답답해하던 중, 알게 된 것이다. 이것만 있으면 새로고침도 두렵지 않다.

 

  1. redux-persist를 설치한다 (예: npm i redux-persist)
  2. root reducer를 persistConfig 설정한다.
  3. react의 index.js에 적용한다.

 

// 2번 과정
import { combineReducers } from "redux";
import userReducer from "./userReducer";	
import storage from "redux-persist/lib/storage";	// localStorage를 이용한다고 한다.
import { persistReducer } from "redux-persist";
// import storageSession from 'redux-persist/lib/storage/session' -> session storage를 이용한다고 한다.

const persistConfig = {
  key: "root", 	// localStorage key
  storage, 		// localStorage
  whitelist: ["userReducer"], // target (reducer name)
};

const rootReducer = combineReducers({ userReducer });

export default persistReducer(persistConfig, rootReducer);


// 3번 과정
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { createGlobalStyle } from "styled-components";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
import { store, persistor } from "./redux/store/store";			// V
import { PersistGate } from "redux-persist/integration/react";	// V

const GlobalStyle = createGlobalStyle`...`;

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter>
    <GlobalStyle />
    <Provider store={store}>
      <PersistGate persistor={persistor}>	// persistGate 설정
        <App />
      </PersistGate>
    </Provider>
  </BrowserRouter>
);
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함