recoil 전역상태관리 라이브러리
npm i recoil
index.js에 RecoilRoot로 감싸기
import { RecoilRoot } from 'recoil';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<RecoilRoot>
<App />
</RecoilRoot>,
);
✨ Atom의 key값은 전역적으로 유일해야한다.!! 중복금지!!!
import { atom } from 'recoil';
export const UserAtom = atom({
key: 'UserAtom',
default: [],
});
useState는 value와 set함수를 같이 선언해야했는데
RecoilState는 따로따로 사용할 수 있다.
export const counterSelector = selector({
key: 'counterSelector',
get: ({ get }) => {
const count = get(CounterStateAtom);
return count * 2;
},
});
import { useRecoilState, useRecoilValue } from 'recoil';
import {
counterSelector,
CounterStateAtom,
} from './../recoil/CounterStateAtom';
const MainPage = () => {
const [count, setCount] = useRecoilState(CounterStateAtom);
const double = useRecoilValue(counterSelector);
function increment() {
setCount(count + 1);
}
function decrement() {
setCount(count - 1);
}
return (
<div>
<div>
<h1>{count}ddddd</h1>
<h1>{double}ddddd</h1>
<button onClick={increment}>up</button>
<button onClick={decrement}>down</button>
</div>
</div>
);
};
export default MainPage;