기존에 채팅을 저장할 때 아래와 같이 chatLogAtom에 모든 방에 대한 채팅을 저장했었다.
export const chatLogAtom = atom<Record<string, Map<string, ChatLog>>>({
key: 'chatLogAtom',
default: {},
});
export interface ChatLog {
message: string;
userId: string;
type: 'message' | 'in' | 'out' | 'kick';
time: Date;
}
하지만 위의 방식은 recoil의 철학과 맞지 않는다.
recoil은 atomic 모델 기반이기 때문이다. 여기서 atom이란 작은상태를 의미한다.
즉, 아래 사진 처럼 하나의 상태가 최대한 작은 상태여야하고 하나의 상태가 하나의 컴포넌트를 구독해야한다.
하지만 우리의 atom은 모든 방의 채팅 데이터를 저장하고 있으므로 옳은 방향이 아니다. 따라서 개별 방마다 atom을 생성할 수 있도록 atomFamily를 사용해보자.
atomFamily는 다음과 같이 사용할 수 있다.
export const chatLogAtom = atomFamily<Map<string, ChatLog>, string>({
key: 'chatLogAtom',
default: new Map(),
});
그 다음 사용하는 곳에서 개별 id를 부여한다.