나는 리덕스를 계속해서 사용해왔지만 Redux-persist에 대해서는 잘 몰랐다.
그런데 이번에 백엔드가 없는 프론트엔드만 있는 프로젝트를 만들면서
새로고침하면 데이터가 다 사라지는게 익숙치 않아졌다.. ㅋㅋㅋ...
평소엔 백엔드를 무조건 같이 구현하니까
새로고침하면 get으로 데이터를 불러와서 데이터가 날아갈 일이 없는데
프론트엔드만 구현해놓으니
새로고침하면 날아가는 데이터에 당황당황 ..
그래서 찾아보다 나온것이 redux-persist 였고,
회사에서 하고 있는 프로젝트에도 사용되고 있다는 사실을 알았다 ..🫣
사용하고 있으면서도 몰랐던 redux-persist에 대해서 제대로 알아보기 ..!
공식문서를 함께 살펴보자!
리덕스 상태를 지속적으로 저장하고 복원하기 위한 라이브러리이다.
새로고침해도 데이터를 유지할 수 있다.
리덕스로 전역 상태관리를 하고 -> redux-persist로 데이터를 유지하고 있을 수 있다.
npm instsall redux-persist
import { createStore } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web
import rootReducer from './reducers'
const persistConfig = {
key: 'root',
storage,
}
const persistedReducer = persistReducer(persistConfig, rootReducer)
export default () => {
let store = createStore(persistedReducer)
let persistor = persistStore(store)
import { PersistGate } from 'redux-persist/integration/react';
import { persistStore } from 'redux-persist';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
const store = createStore(persistedReducer);
const persistor = persistStore(store);
ReactDOM.render(
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>,
document.getElementById('root')
);
=> 이렇게 하면 지속된 상태가 검색되어 redux에 저장될 때 까지의 앱 UI 렌더링이 지연된다.
이렇게 하면 아주 간단하게 redux-persist를 적용할 수 있다.
공식문서에서 가져온 기본 활용법을 보면 눈치챘을 수도 있지만,
그럼 데이터가 어디에 저장되길래 새로고침해도 유지돼?
브라우저 저장소를 활용한다.
localstorage나 sessionstorage 등 저장공간에 데이터를 저장하여 데이터를 유지할 수 있다.
실제로 redux-persist를 적용하고 확인해보면
나의 경우에는 따로 설정을 하지 않았기 때문이 기본 저장소인 localstorage에
리듀서의 데이터들이 객체 형태로 담겨있었다.
나는 간단한 모듈을 만들고 있었고, 새로고침하면 데이터가 남아있길 바래서
redux-persist 라이브러리를 설치하고 적용해보았다.
import { configureStore } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import pageReducer from "../features/PageSlice";
const persistConfig = {
key: 'root',
storage,
}
const persistedReducer = persistReducer(persistConfig, pageReducer)
export default () => {
let store = createStore(persistedReducer)
let persistor = persistStore(store)
}
이렇게 아주 간단하게 구현할 수 있었고, 실제로 새로고침해보니 데이터가 유지됐다!
그러나 나는 결국 신나서 구현해놓은 redux-persist를 쓰지 않았다.
그 이유는, 각 페이지마다 유효성 검사가 있었다.
특히나 첫번째 페이지 같은 경우는 라디오버튼 4개 중 값을 골라야한다.
그러나 아무값도 선택하지 않았을 때는 유효성 검사에 걸려 alert가 나와야한다.
그러나 한 번 데이터를 선택하고 나면 얘가 데이터를 계속 물고 있어
유효성 검사 테스트를 할 수가 없었다..🥹
그리고 큰 프로젝트가 아니라 단순 프로젝트였기 때문에
페이지 넘어갈 때만 데이터를 유지하면 되므로
리덕스만으로도 충분히 가능했다.
그래서 나의 경우에는 redux-persist를 결국 쓰지 않았지만
그래도 활용하기 너무 좋은 라이브러리라고 생각이 들어
따로 더 공부해보았다!
그럼 이만 -!
https://github.com/rt2zz/redux-persist
https://velog.io/@bcl0206/%EC%83%88%EB%A1%9C%EA%B3%A0%EC%B9%A8-%ED%9B%84%EC%97%90%EB%8F%84-store-state-%EC%9C%A0%EC%A7%80%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95-Redux-persist