recoil
npm i recoil
RcoilRoot
recoil 상태를 사용하는 컴포넌트는 부모 트리에 RecoilRoot 가 필요하다.
import {
RecoilRoot,
atom,
selector,
useRecoilState,
useRecoilValue,
} from "recoil";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<RecoilRoot>
<App />
</RecoilRoot>
</StrictMode>
);
Atom
Atom은 상태(state) 의 일부, atom 의 값을 읽는 컴포넌트는 atom 을 구독한다.
구독하는 컴포는트는 atom의 상태 변화가 있으면 rerender한다 .
const textState = atom({
key: "textState", // unique ID
default: "", // default value
});
- useRecolilState
상태 get 값, setter 필요할 시 useRecoilState를 사용(useState와 비슷)
function TextInput() {
const [text, setText] = useRecoilState(textState);
const onChange = (event) => {
setText(event.target.value);
};
return (
<div>
<input type="text" value={text} onChange={onChange} />
<br />
Echo: {text}
</div>
);
}
- useRecoilValue
상태 get 값
function CharacterCount() {
const count = useRecoilValue(textState);
return <>Character Count: {count}</>;
}
useSetRecoilState
업데이트 setter 함수만 받아 오고 싶을땐 useSetRecoilState()
훅을 사용 할 수 있다.
const setTodoList = useSetRecoilState(todoListState);
const addItem = () => {
setTodoList((oldTodoList) => [
...oldTodoList,
{
id: getId(),
text: inputValue,
isComplete: false,
},
]);
setInputValue("");
};
const onChange = ({ target: { value } }) => {
setInputValue(value);
};
Selector
- selector는 하나 이상의 atom 또는 selecotr 를 기반으로 새로운 값을 개산
(set 함수 사용 시 쓰기 가능한 seltor로 만들 수 있다.) - 비동기 작업 지원
Selector 는 비동기 함수를 사용하여 데이터를 가져와서 계산이 가능,
API 호출과 같은 비동기 작업을 쉽게 처리
import { selector, useRecoilState } from "recoil";
import { todoListState } from "./atoms";
const todoListStatsState = selector({
key: "todoListStatsState",
get: ({ get }) => {
const todoList = get(todoListState);
const total = todoList.length;
const completed = todoList.filter((todo) => todo.isCompleted).length;
return { total, completed };
},
set: ({ set }, newValue) => {
// 새로운 값을 받아 todoListState를 업데이트
set(todoListState, newValue);
},
});
// 사용 예시
function TodoListStats() {
const [stats, setStats] = useRecoilState(todoListStatsState);
return (
<div>
<p>Total: {stats.total}</p>
<p>Completed: {stats.completed}</p>
</div>
);
}
'React🦄' 카테고리의 다른 글
React-Hook_Form (0) | 2025.02.16 |
---|---|
SVG파일, Component 사용하기!(for Vite + TypeScript) (0) | 2025.02.03 |
useRef는 뭘까아요~~~? (0) | 2025.01.24 |