티스토리 뷰

반응형

Redux-Persist

React의 Redux-Persist를 사용하면 새로고침을 해도 데이터가 지속적으로 유지된다.

 


 

 

이 글에선 Redux-Persist를 Redux-Toolkit과 함께 사용하여 알아볼 예정이다.

 

먼저 프로젝트를 설치하자

 

CRA 설치

# Redux + Plain JS template
npx create-react-app my-app --template redux

 

기존

# NPM
npm install @reduxjs/toolkit

# Yarn
yarn add @reduxjs/toolkit

 

 

파일 구조

 

├── README.md
├── node_modules
├── package.json
├── public
└── src

 

 


 

 

새로고침을 해도 데이터를 유지하는 것을 적용하기 전에 먼저 현재 상태를 확인해보자.

 

npm start를 사용하여 프로젝트를 실행하면 다음과 같은 화면이 나온다.

여기서 count를 올리고 새로고침(F5)을 누르면 데이터가 초기화된다.

 

 


 

 

지금부터 Redux-Persist를 사용하여 새로고침 버튼을 눌러도 데이터를 유지시켜보자.

 

 

src/app/store.jssrc/index.js을 수정하여 변경할 예정이다.

 

✒️ src/app/store.js

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';

export default configureStore({
  reducer: {
    counter: counterReducer,
  },
});

 

✒️ src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { store } from './app/store';
import { Provider } from 'react-redux';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

 

 


 

시작

# NPM
npm install redux-persist

# Yarn
yarn add redux-persist

먼저 redux-persist 패키지를 설치한다.

 

 

그리고 위에 말했던 src/app/store.js 파일을 열어서 다음과 같이 추가 수정한다.

 

 

✒️ src/app/store.js 수정

import { configureStore } from '@reduxjs/toolkit';
import storage from 'redux-persist/lib/storage';
import { combineReducers } from 'redux';
import { persistReducer } from 'redux-persist';
import thunk from 'redux-thunk';

import counterReducer from '../features/counter/counterSlice';

const reducers = combineReducers({
  counter: counterReducer,
});

const persistConfig = {
  key: 'root',
  storage,
};

const persistedReducer = persistReducer(persistConfig, reducers);

const store = configureStore({
  reducer: persistedReducer,
  devTools: process.env.NODE_ENV !== 'production',
  middleware: [thunk],
});

export default store;

 

 

src/app/store.js 파일도 다음과 같이 추가 수정한다.

 

 

 

✒️ src/index.js 수정

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { store } from './app/store';
import { Provider } from 'react-redux';
import * as serviceWorker from './serviceWorker';
import { PersistGate } from 'redux-persist/integration/react';
import { persistStore } from 'redux-persist';

let persistor = persistStore(store);

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <App />
      </PersistGate>
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

 

 

redux-persist를 성공적으로 적용했다.

이제 새로고침을 해도 데이터가 계속 유지된다.

 

 


 

 

결과 확인

 

 

 

참고 사이트

리덕스 툴킷 공식 사이트(en)

how-to-use-redux-persist-with-redux-toolkit

 

 

 

좋아요는 로그인하지 않아도 누를 수 있습니다!

728x90
반응형

'FRONT-END' 카테고리의 다른 글

[React] map 함수 사용 시 Key 값을 부여해 주는 이유  (2) 2022.04.26
[React] .env (환경변수 관리)  (4) 2022.03.17
[Vue] V-Calendar  (0) 2021.11.02
[Vue] Vue 인스턴스  (0) 2021.08.31
[Vue] Vue란?  (0) 2021.08.31
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함