상세 컨텐츠

본문 제목

[React] Recoil Selector

React

by 일단두잇 2023. 3. 1. 21:32

본문

반응형

 

그러면, selector는 무엇일까?

 

단순하게, 정의하면 state를 다양한 형태로 조회하게 해주는 방법이다.

- state관리를 위해 recoil을 사용하고 화면과 분리하여 state를 관리하고자 recoil을 사용하는 이유인데,

화면에서 다시 state를 관리하는 로직이 있다면, 본래 취지와 어긋나서 비지니스 로직이 파편화되는

문제가 발생할 수 밖에 없다.

따라서, recoil에서 selector를 제공하여 state를 관리하는 로직까지 같이 포함하는 것이다.

 

사용 Case를 보면,

  1. state를 가져와서(get) 다른 값으로 변경(set) 하거나
  2. 여러 state를 가져와서 조합하거나
  3. Rest API와 조합하여 서버데이터를 관리 할수도 있다.

 

여기서 중요한 부분은 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);
  },
});
 

 

 

반응형

관련글 더보기

댓글 영역