Redux Persist 알아보기

휴먼스케이프

Redux와 Redux Persist를 사용하여 앱을 종료해도 지속되는 Store 만들기

안녕하세요. 휴먼스케이프에서 개발자로 일하고 있는 Henry입니다. 이번 포스트에서는 Redux Persist 라이브러리를 소개하려고 합니다.

소개

React나 React Native와 같이, 혹은 단독으로 쓰일 수 있는 Redux라는 매력적인 상태 관리 라이브러리가 널리 쓰이고 있습니다.

하지만 리덕스의 Store는 앱을 종료하면 저장되어 있던 모든 상태가 없어집니다. 그래서 캐시 기능을 구현하는 또다른 장치가 필요합니다. 예를 들어 웹에서는 LocalStorage, 네이티브에서는 AsyncStorage 등을 써서 상태를 저장하고 불러쓰곤 합니다.

Redux Saga에서 토큰을 불러내는 작업 도중, AsyncStorage에서 토큰의 유무를 체크합니다.

위의 예시처럼 토큰만 저장하게 된다면 괜찮으나, 무수히 많은 정보를 저장하기에는 위와 같은 방식대로 한다면 그만큼의 불필요한 시간이 증가하게 됩니다.

이런 상황에서 Redux Persist를 사용하면 이런 작업들을 단번에 처리할 수 있습니다.

사용해보기

환경

Web App

React (or None)

Redux

Redux Persist

프로젝트 세팅

새 리액트 프로젝트를 생성합니다.

$ npx create-react-app persisted-counter
$ cd persisted-counter

그리고 필요한 라이브러리들을 설치해줍니다.

$ npm i --save redux react-redux redux-persist

기본 파일들을 삭제하고 불필요한 import 및 구문들을 제거한 뒤, 아래처럼 구조를 만들어줍니다.

앱의 구조

리듀서 및 스토어

우선 src/reducers/counter.reducer.js 파일에서 Counter Reducer부터 만들어줍니다.

그 후 src/reducers/index.js 파일에서 Root Reducer를 만듭니다.

리듀서가 완성되면 store/index.js 파일에서 스토어를 만들어줍니다.

컴포넌트 및 컨테이너

차례대로 Counter 및 CounterContainer를 만들어줍니다.

그 다음 index.js와 App.js를 세팅합니다.

구동되는 모습

새로고침을 하고도 유지되는 Counter의 상태

번외

사용 가능한 Storage

아래 링크에 Web 혹은 Native 환경에서 사용할 수 있는 Storage 목록이 있습니다.

rt2zz/redux-persist Persist and rehydrate a redux store. npm install redux-persist Usage Examples: Basic Usage Basic usage involves adding…github.com

참고용 Github Repository

hw0k/persisted-counter You can't perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com

이상으로 Redux Persist 소개를 마치겠습니다. 감사합니다.

Get to know us better! Join our official channels below.

Telegram(EN) : t.me/Humanscape KakaoTalk(KR) : open.kakao.com/o/gqbUQEM Website : humanscape.io Medium : medium.com/humanscape-ico Facebook : www.facebook.com/humanscape Twitter : twitter.com/Humanscape_io Reddit : https://www.reddit.com/r/Humanscape_official Bitcointalk announcement : https://bit.ly/2rVsP4T Email : support@humanscape.io

기업문화 엿볼 때, 더팀스

로그인

/