react를 사용 할때 다들 이러한 경험이 있을 것이다 1.부모 컴포넌트에서는 props 가 필요없지만 2.자식 컴포넌트에서 필요한 값을 위해서 0.조상 컴포넌트에서 1.부모를 거처서 2.자식컴포넌트로 props를 넘기는 경우를

이러한 경우 때문에 상태관리를 위한 여러 라이브러리가 존재한다.
상태관리 라이브러리를 사용하면 0.조상, 1.부모 컴포넌트를 거치지 않고 바로 2.자식컴포넌트에서 사용할 수 있다.

react에서 자체 제공하는 Context API와 대표적인 라이브러리 Redux, Mobx, recoil 중 recoil을 알아보자
atom은 하나의 상태의라고 볼 수 있다. 컴포넌트가 구독할 수 있는 React state라고 생각하면 된다. atom의 값을 변경하면 그것을 구독하고 있는 컴포넌트들이 모두 다시 렌더링된다.
export const todoListState = atom({
key: "searchKeyword",
default: 'reocil이란 뭘까?',
})
const [search, setSearch] = useReocilState(todoListState)
console.log(search) -> reocil이란 뭘까?
setSearch('상태관리 해주는 라이브러리 입니다!')
console.log(search) -> 상태관리 해주는 라이브러리 입니다!
useRecoilState — atom의 값을 구독하여 업데이트할 수 있는 hook의 useState 와 동일한 방식으로 사용할 수 있다.
useRecoilValue — setter 함수 없이 atom의 값을 반환만 한다.
useSetRecoilState — setter 함수만 반환한다.
import { atom, selector } from "recoil";
export const todoListState = atom({
key: "todoListState",
default: [{
title: "아침밥먹기",
id: 1,
isCompleted: false
},
{
title: "점심밥먹기",
id: 2,
isCompleted: false
},{
title: "저녁밥먹기",
id: 3,
isCompleted: false
}
]
})
// 할일 필터링 목록
export const todoListFilterState = atom({
key: "todoListFilterState",
default: 'Show All',
})
// 파생된 할일 필터링 목록
export const filteredTodoListState = selector({
key: "filteredTodoListState",
get: ({get}) =>{
const filter = get(todoListFilterState);
const list = get(todoListState);
switch (filter){
case 'Show Completed':
return list.filter((item) => item.isComplete);
case 'Show unCompleted':
return list.filter((item) => !item.isComplete);
default:
return list;
}
}
})
다음은 selecter를 활용한 비동기 데이터 통신에 대하여 알아 보겠다.