Recoil SelectorFamily에 대해 알아보려 한다.
정의
Recoil 공식 사이트에 SelectorFamily에 대해 다음과 같이 정의가 되어있다.
A selectorFamily is a powerful pattern that is similar to a selector, but allows you to pass parameters to the get and set callbacks of a selector. The selectorFamily() utility returns a function which can be called with user-defined parameters and returns a selector. Each unique parameter value will return the same memoized selector instance.
해당 글을 번역기를 돌려보면 다음과 같다.
selectorFamily는 강력한 패턴으로, selector와 유사하지만 get 및 set 콜백에 매개변수를 전달할 수 있다는 점에서 차이가 있습니다. selectorFamily() 유틸리티는 사용자 정의 매개변수를 사용하여 호출될 수 있는 함수를 반환하며, 그 결과로 selector를 반환합니다. 각 고유한 매개변수 값에 대해 동일한 메모이제이션된 selector 인스턴스를 반환합니다.
즉. Recoil Selector와 차이점은 매개 변수를 넣을 수 있다는 것이다.
사용법 알아보기
다음은 atoms라는 파일에 RecoilState를 examState 정의하고,
selectorFamily를 examSelector라는 이름으로 정의하였다.
atoms.ts
export const examState = atom<number[]>({
key: "exam"
default: [1, 2, 3]
});
export const examSelector = selectorFamily({
key: "examKey",
get:
({ param1, param2 }: { num1: number; num2: number}) => // {param1, param2} 객체로 써주기
({ get }) => {
const nums = get(examState);
const result = nums.map((num)=> num1 * param2 * param2));
return result
},
});
위의 코드를 간단하게 설명하면, param1 param2를 객체 형태로 매개 변수로 받고 examState 배열 안의 원소 값에 param1 param2를 곱해주는 것이다. 참고로 매개변수로 보낼 때는 객체 형태로 해줘야 한다는 것을 잊지 말자.
컴포넌트에서 사용할 때는 다음과 같다.
Home.tsx
export default function Home() {
const exam = useRecoilValue(examSelector({ num1 : 3, num2: 4 }));
console.log(exam); // [1 * 3 * 4, 2 * 3 * 4, 3 * 3 * 4]
return (
<>
<>
<ExamPage exam={exam}>
/>
</>
</>
);
}
먼저 위에서 정의한 selectorFamily를 사용하기 위해서는 다음과 같이 불러오면 된다.
useRecoilValue(selectorFamily(객체 매개변수)); ex) useRecoilValue(examSelector({ num1 : 3, num2: 4 }));
'React' 카테고리의 다른 글
[React] react-paginate with styledComponent (1) | 2024.10.12 |
---|---|
[React] Tailwindcss, Styled Components 연동 (0) | 2022.09.29 |
[React] react typescript can't resolve './app' 에러 (0) | 2022.09.28 |
[React] tailwindcss 설치 (0) | 2022.09.28 |