리덕스는 새로고침하거나 창을 닫으면 스토어에 저장된 state가 리셋된다. 로그인 정보를 store에서 관리하는 경우, 해당 state가 유지되어야 한다. 이 때 redux-persist를 사용하면 된다.
npm i redux-persist
or yarn add redux-persist
TypeScript
npm i redux-persist @types/redux-persist
or yarn add redux-persist @types/redux-persist
import storage from 'redux-persist/lib/storage
import sessionStorage from 'redux-persist/lib/storage
import { combineReducers } from 'redux';
import authReducer from './authReducer';
import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
// config 작성
const persistConfig = {
key: "root", // localStorage key
storage, // localStorage
whitelist: ["auth"], // target (reducer name)
}
const rootReducer = combineReducers({
auth: authReducer
});
// persistReducer로 감싸기
export default persistReducer(persistConfig, rootReducer);
(state/Store.tsx)
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';
import thunk from 'redux-thunk';
import { persistStore } from 'redux-persist';
import { composeWithDevTools } from "redux-devtools-extension"; // 개발자 도구
export const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk))); // 기존 store 내보내기
export const persistor = persistStore(store); // persist store 내보내기
export type RootReducerType = ReturnType<typeof rootReducer>;
(index.tsx)
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Provider } from "react-redux";
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistor } from './state/Store';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<Provider store={store}>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</Provider>
);