[recoil] recoilpersist를 사용하여 localstorage 저장하기

dolfin·2023년 1월 20일
0

React

목록 보기
2/13
post-thumbnail

recoil-persist ?

react 프로젝트에서 전역상태관리를 recoil로 선택하게 되었다.

새로고침시 전역상태관리가 초기화되는 문제가 발생하여,
local storage로 저장을 하게 되었는데

recoil-persist라는 라이브러리를 사용하면 더 편리하게 local storage를 사용할 수 있는 것을 알게되어 사용하게 되었다.

설치

npm instll recoil-persist

사용법

import { recoilPersist } from 'recoil-persist';
import { atom, useRecoilState } from 'recoil';

const { persistAtom } = recoilPersist(); 
// persistAtom을 불러와준다. 이렇게 작성하는 것만으로도 기본적으로
// localStorage에 저장되며, key 이름은 기본적으로 'recoil-persist'로 저장된다

키 이름이나 스토리지 변경하려면 아래와 같이 코드 작성

const { persistAtom } = recoilPersist({
 key: '내맘대로 정하는 키 이름',
 storage: sessionStorage,
});
const 변수명 = atom({
  key: '키값', // 로컬스토리지에 저장되는 키값
  default: [], // 로컬스토리지에 저장되는 초기값
  effects_UNSTABLE: [persistAtom], // (필수)위에서 불러온 persistAtom 넣어줌
});

사용해보진 않았지만
redux에서는 동일한 기능인 redux-persist가 있다고 한다.

recoil-persist 는 개인적으로 너무 사용이 편리해서 좋았는데,
검색을 하면서 업데이트가 1년동안 진행되고 있지 않아 안정적이지 않은 라이브러리 같다는 평이 있어서 큰 프로젝트내에서는 사용시 유의해야할 것 같다라는 생각이 든다.

공식사이트 : https://www.npmjs.com/package/recoil-persist

profile
no risk no fun

0개의 댓글