WEB/REACT

[REACT] redux-persist를 사용하여 새로고침 시에도 리덕스 상태 유지하기

자바칩 프라푸치노 2022. 2. 8. 20:09

소개

redux는  새로고침 시에 상태들이 모두 날라가는 반면

redux-persist를 이용하면 로컬 스토리지에 저장이 된다. 

그래서 원래 리덕스처럼 사용하는데 새로고침 시에 날라가지 않고 개발자도구에서 삭제 할 때 까지 유지된다. 

 

 

설치

yarn add redux-persist

 

 

코드

 

store/index.js

 

//store/index.js
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import { createBrowserHistory } from 'history';
import { routerMiddleware } from 'connected-react-router';
import reducers from '../reducers';
1️⃣import storage from 'redux-persist/lib/storage';
2️⃣import persistReducer from 'redux-persist/es/persistReducer';
3️⃣import persistStore from 'redux-persist/es/persistStore';
const history = createBrowserHistory();
const routeMiddleware = routerMiddleware(history);
const bindMiddleware = middleware => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension');
const { logger } = require('redux-logger');
middleware.push(logger);
return composeWithDevTools(applyMiddleware(...middleware));
}
return applyMiddleware(...middleware);
};
4️⃣const persistConfig = {
key: 'root',
storage,
whitelist: ['history'] //여기있는 모듈만 persist를 사용
//blacklist는 해당 모듈을 제외
}
5️⃣const persistedReducer = persistReducer(
persistConfig,
reducers(history)
)
function configureStore(initialState = {}) {
const store = createStore(
6️⃣persistedReducer,
initialState,
bindMiddleware([routeMiddleware, thunk.withExtraArgument(history)]),
);
7️⃣const persistor = persistStore(store)
return {store, persistor};
}
export default configureStore;
export { history };
view raw index.js hosted with ❤ by GitHub

 

 

//App.js
import React from 'react';
..생략
import { PersistGate } from 'redux-persist/integration/react';
export const {store, persistor} = configureStore();
const App = () => (
<Provider store={store}>
<ConnectedRouter history={history}>
<PersistGate loading={null} persistor={persistor}>
..
<Switch>
<Routes />
</Switch>
..
</PersistGate>
</ConnectedRouter>
</Provider>
);
export default App;
view raw App.js hosted with ❤ by GitHub

 

 

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

이렇게 설정해주고 원래 쓰던대로 쓰면 됨

728x90