-
[전역상태관리] Recoil프로그래밍/React 2023. 11. 2. 21:03
recoil을 사용하기에 앞서 상태관리라이브러리로써 가장 많이 사용되는 Redux와 비교를 안해볼 수 없다.
상태관리 비교
개요
- RecoilRoot
- Atom
- Selector
- Recoil-persist
RecoilRoot
export const App = () => { return ( <RecoilRoot> <App /> </RecoilRoot> ) }
Atom
import {atom} from 'recoil'; export const todoState = atom({ key: "todoState", default: [] })
장점
- Redux에 비해 적은 boilder plate
- 사용하기 편한 구조
Recoil에서 가장 좋은 점은 학습하기 쉬운 구조로 되어있다는 것이다.
React를 사용하면 기본적으로 사용하게 되는 useState와의 구조가 매우 흡사하기 떄문이다.
- useRecoilState (value와 setter)
- useSetRecoilState (setter)
- useRecoilValue (value)
- useResetRecoilState (reset value)
4가지 방법을 통해서 state를 get하고 set하고 reset하는 방법을 알 수 있다.
Selector
atom을 기반으로 파생된 데이터를 만들어내는데 사용이 된다.
import { selector } from "recoil"; import { todoState } from "../atoms/todoState"; export const todoSortState = selector({ key: "todoSortState", get: ({ get }) => { const data = get(todoState); const result = data.filter((v) => v.state === true) return result } })
Recoil-persist
새로고침을 했을 때 state값이 사라지거나 변경되지 않아야하는 경우 Storage를 이용하는 경우가 있는데 그 떄 사용하는 것임.
import { atom } from "recoil"; import { recoilPersist } from "recoil-persist"; const { persistAtom } = recoilPersist({ key: "sessionStorage", //원하는 key 값 입력 storage: sessionStorage, }) export const mbtiState = atom({ key: "mbtiState", default: [], effects_UNSTABLE: [persistAtom] })
'프로그래밍 > React' 카테고리의 다른 글
[Article] React 렌더링 동작에 대한 (거의) 완벽한 가이드(1편) (0) 2023.11.21 [SWR] Data의 reavalidate, mutate 활용 (0) 2023.11.03 [React] react-router-dom의 사용 (1) 2023.10.04 [Vite] ESlint 와 Prettier, Package.json 초기설정 (0) 2023.10.02 [제로초 Slack 클론 코딩] 백엔드 준비 + 초기설정 (Day-1) (0) 2023.09.29