React와 같은 SPA는 여러 컴포넌트간의 관계, 즉 state관리가 가장 중요한데,
Recoil을 사용하면 State(Recoil Atom)를 관리할 수 있다.
그러면, selector는 무엇일까?
단순하게, 정의하면 state를 다양한 형태로 조회하게 해주는 방법이다.
- state관리를 위해 recoil을 사용하고 화면과 분리하여 state를 관리하고자 recoil을 사용하는 이유인데,
화면에서 다시 state를 관리하는 로직이 있다면, 본래 취지와 어긋나서 비지니스 로직이 파편화되는
문제가 발생할 수 밖에 없다.
따라서, recoil에서 selector를 제공하여 state를 관리하는 로직까지 같이 포함하는 것이다.
사용 Case를 보면,
여기서 중요한 부분은 state가 변경될때 마다 selector도 재조회 한다는 점이다.
selector를 사용하는 가장 중용한 이유이자, 주의해야할 부분이다.
구현방법
key: 유니크한 Key
get: atom이나 seletor를 반환
- get: atom을 조회
set: atom의 값을 변경
- get : atom을 조회
- set : atom을 변경
function selector<T>({
key: '',
get: ({
get: GetRecoilValue,
getCallback: GetCallback,
}) => T | Promise<T> | Loadable<T> | WrappedValue<T> | RecoilValue<T>,
set?: (
{
get: GetRecoilValue,
set: SetRecoilState,
reset: ResetRecoilState,
},
newValue: T | DefaultValue,
) => void,
})
사용 예
import { atom, selector } from 'recoil';
export interface IAlert {
title?: string;
content?: string;
}
export const alertAtom = atom<IAlert>({
key: 'common/alert',
default: {
title: '',
content: '',
},
});
const alertAtomSelector = selector<IAlert>({
key: 'common/alert/selector',
get: ({ get }) => {
const alert = get(alertAtom);
return { title: '제목 : ' + alert.title, content: '내용' + alert.content };
},
set: ({ get, set }, newValue: IAlert | DefaultValue) => {
const alert: IAlert = get(alertAtom);
const newAlert: IAlert = {
title: (newValue as IAlert).title || alert.title,
content: (newValue as IAlert).content || alert.content,
close: (result: string) => console.log(result),
};
set(alertAtom, newAlert);
},
});
[React] Infinite scroll(2) - React query + Recoil + 최적화 (0) | 2023.03.08 |
---|---|
[React] Infinite scroll (1) - React query (0) | 2023.03.08 |
React Query - useQuery 맛보기 (0) | 2023.03.01 |
React 조건부 Rendering시 주의점 (0) | 2023.03.01 |
React + immer 를 사용한 불변성 관리 (feat. recoil) (0) | 2023.02.18 |
댓글 영역