Redux 상태를 로컬 스토리지나 앱 내 파일 시스템에 지속적으로 저장하고 관리하기 위한 라이브러리이다.
npm install redux-persist
# 필수 설치 아님. expireReducer가 필요할 때 설치하기!
npm install redux-persist-expire
import { configureStore } from '@reduxjs/toolkit';
import storage from 'redux-persist/lib/storage'; // storage 가져오기
// import storageSession from 'redux-persist/lib/storage/session'; => session 가져오기
import { combineReducers } from 'redux';
import { persistReducer } from 'redux-persist'; // persistReducer 가져오기
// import expireReducer from 'redux-persist-expire';
import { userSlice } from '../reducer/userSlice';
import { authSlice } from '../reducer/authSlice';
import askSlice from '../reducer/askSlice';
import questionSlice from '../reducer/questionSlice';
const reducers = combineReducers({
user: userSlice.reducer,
auth: authSlice.reducer,
ask: askSlice.reducer,
questions: questionSlice.reducer,
});
const persistConfig = {
key: 'root',
storage,
whitelist: ['user', 'auth'], // whitelist => 이 키만 저장
blacklist: ['ask', 'questions'], // blacklist => 이 키만 저장 안함
transforms: [
expireReducer('auth', {
expireSeconds: 3600, // 만료 시간 (초)
autoExpire: true,
persistedAtKey: 'auth_exp',
expiredAction: removeToken,
// expiredState: { token: null, isAuthenticated: false }, // 만료되었을 때 설정할 값
}),
expireReducer('user', {
expireSeconds: 3600,
autoExpire: true,
persistedAtKey: 'user_exp',
expiredAction: logout,
}),
],
};
const persist = persistReducer(persistConfig, reducers);
const store = configureStore({
reducer: persist,
middleware: (getDefaultMiddleware) => getDefaultMiddleware({ serializableCheck: false }),
});
export default store;
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { persistStore } from 'redux-persist';
import store from './store/store';
import './index.css';
import App from './App';
export let persistor = persistStore(store);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<PersistGate loading={null} persistor={persistor}>
<Provider store={store}>
<App />
</Provider>
</PersistGate>
</React.StrictMode>,
);