Recoil
์์ ๊ฐ์ฅ ๊ธฐ๋ณธ์ ์ธ ์ํ ๋จ์export const ExAtom = atom({
key: 'ํค๊ฐ',
default: ๊ฐ
})
useRecoilState
์ฌ์ฉํด useState
์ ๋น์ทํ๊ฒ ์ฌ์ฉconst [value, setValue] = useRecoilState(ExAtom)
useRecoilValue
: ๊ฐ๋ง ํ์ํ ๊ฒฝ์ฐconst value = useRecoilValue(ExAtom)
useSetRecoilState
: ๋ณ๊ฒฝํจ์๋ง ํ์ํ ๊ฒฝ์ฐconst setValue = useSetRecoilState(ExAtom)
export const ExSelector = selector({
key: 'ํค๊ฐ',
get: ({get}) => {
const ์๋ณธ = get(ExAtom)
return ์๋ณธ์_๋ก์งํตํด_๋ณํํ๊ฐ
}
set: ({set}, ์ธ์๋ก_๋ฐ์์จ๊ฐ) => {
const ๋ณ๊ฒฝํ _์๋ก์ด๊ฐ = ์ธ์๋ก_๋ฐ์์จ๊ฐ์ ๋ณํํ๋๋ก์ง
set(ExAtom, ๋ณ๊ฒฝํ _์๋ก์ด๊ฐ)
}
})
useRecoilState
, useRecoilValue
, useSetRecoilState
์ฌ์ฉ
// ํ๋ฒ์ ์ ์ธํ๊ธฐ
const [selector, setSelector] = useRecoilState(ExSelector)
// get ๊ฒฐ๊ณผ๊ฐ ๊ฐ์ ธ์ค๊ธฐ
const get_๊ฒฐ๊ณผ๊ฐ_๊ฐ์ ธ์ค๊ธฐ = useRecoilValue(ExSelector)
// set ๊ธฐ์กด๊ฐ์์ ๋ณ๊ฒฝ๋ ๊ฐ ๊ฐ์ ธ์ค๊ธฐ
const set_๊ธฐ์กด๊ฐ_๋ณ๊ฒฝํ๊ธฐ = useSetRecoilState(ExSelector)
// ์ ์ฝ๋๋ค์์ ๋ค์์ ๊ฐ์ ๊ฐ
// selector = get_๊ฒฐ๊ณผ๊ฐ_๊ฐ์ ธ์ค๊ธฐ
// setSelector(์ธ์) = set_๊ธฐ์กด๊ฐ_๋ณ๊ฒฝํ๊ธฐ(์ธ์)
UserAtom.js
import { atom, selector } from 'recoil';
export const myNewAtom = atom({
key: 'myNewAtom',
default: 0,
});
export const myNewSelector = selector({
key: 'myNewSelector',
get: ({ get }) => {
const ์๋ณธ = get(myNewAtom);
return ์๋ณธ + 10;
},
set: ({ set }, ์ธ์๋ก_๋ฐ์์จ๊ฐ) => {
const ๋ณ๊ฒฝํ _์๋ก์ด๊ฐ = Number(์ธ์๋ก_๋ฐ์์จ๊ฐ) + 10;
set(myNewAtom, ๋ณ๊ฒฝํ _์๋ก์ด๊ฐ);
},
});
App.js
import { useRecoilState } from 'recoil';
import { myNewAtom, myNewSelector } from './recoil/UserAtom';
export default function App() {
const [atom, setAtom] = useRecoilState(myNewAtom);
const [selector, setSelector] = useRecoilState(myNewSelector);
return (
<>
// ๋ฒํผ1 : ํ์ฌ atom๊ฐ ๋ณด์ฌ์ฃผ๋ ๋ฒํผ
<button onClick={() => {
console.log('ํ์ฌ atom : ' + atom);
}}>
ํ์ฌ atom ๊ฐ ๋ณด๊ธฐ
<div>์ฝ๋: atom</div>
</button>
// ๋ฒํผ2 : setAtom() ํตํด์ atom๊ฐ 1 ์ฆ๊ฐ์ํค๋ ๋ฒํผ
<button onClick={() => {
setAtom((prev) => prev + 1);
console.log('atom๊ฐ +1');
}}>
atom๊ฐ ๋ฐ๊พธ๊ธฐ (+1)
<div>์ฝ๋: setAtom((prev) => prev + 1)</div>
</button>
// ๋ฒํผ3 : get ํตํด์ ์๋ณธ atom๊ฐ ๋ณ๊ฒฝ์ํค์ง ์๊ณ ์๋ณธ๊ฐ์์ 10 ์ฆ๊ฐํ ๊ฐ ๊ฐ์ ธ์ค๋ ๋ฒํผ
<button onClick={() => {
console.log('selector์์ ํ์ฌ atom ๊ฐ์ ธ์ ๋ณํํ ๊ฐ : ' + selector);
console.log("'ํ์ฌ atom ๊ฐ ๋ณด๊ธฐ' ๋ฒํผ์ ํด๋ฆญํด๋ณด์ธ์");
}}>
get ์ด์ฉํด selector์ ์ฐ๊ฒฐ๋ atom์ ์๋๊ฐ ๋ณ๊ฒฝํ์ง์๊ณ , ๋ณํํ ๊ฐ ๊ฐ์ ธ์ค๊ธฐ (+10)
<div>์ฝ๋: selector</div>
</button>
// ๋ฒํผ4 : set ํตํด์ ์๋ณธ atom๊ฐ์ 10 ์ฆ๊ฐ์ํค๋ ๋ฒํผ
<button onClick={() => {
setSelector(atom);
console.log('setSelector(์ธ์)์์ ์ธ์๋ก ๋ค์ด์จ ๊ฐ + 10');
console.log("'ํ์ฌ atom ๊ฐ ๋ณด๊ธฐ' ๋ฒํผ์ ํด๋ฆญํด๋ณด์ธ์");
}}>
set ์ด์ฉํด selector์ ์ฐ๊ฒฐ๋ atom์ ์๋๊ฐ์ ๋ณ๊ฒฝํ๊ธฐ (+10)
<div>์ฝ๋: setSelector(atom)</div>
</button>
</>
);
}