3. Selectors
Selector ๋ ์ํ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ์ ๋ฌ๋ ๋ฐ์ดํฐ๋ฅผ ๊ฐ๊ณตํ ๋ ์ฌ์ฉ๋ฉ๋๋ค.
selector()
ํจ์์ key ์ get ์ set ๋ฅผ ์ ๋ฌํ์ฌ ์์ฑํฉ๋๋ค.
import { selector } from 'recoil';
...
const fontSizeLabelState = selector({
key: 'fontSizeLabelState',
get: ({get}) => {
const fontSize = get(fontSizeState);
const unit = 'px';
return `${fontSize}${unit}`;
},
});
get
ํ๋กํผํฐ๋ ๊ณ์ฐ์ ์ฌ์ฉ๋๋ ํจ์์
๋๋ค.
์ ๋ฌ๋ get
์ธ์๋ฅผ ์ฌ์ฉํด์ ์ํฐ(Atom)์ด๋ ๋ค๋ฅธ ์
๋ ํฐ(Selector)์ ์ ๊ทผํ ์ ์์ผ๋ฉฐ, ์ ๊ทผํ ์ํฐ์ด๋ ์
๋ ํฐ๊ฐ ์
๋ฐ์ดํธ ๋๋ฉด ๋ค์ ๊ณ์ฐ๋ฉ๋๋ค.
์ ์์ ์ ์
๋ ํฐ๋ fontSizeState
์ํ๋ฅผ ๊ฐ์ ธ์ ํฐํธ ์ฌ์ด์ฆ๋ฅผ ์ถ๋ ฅํ๋ ์์ ํจ์์ฒ๋ผ ๋์ํฉ๋๋ค.
์
๋ ํฐ๋ ์ธ ์(write)์๊ธฐ ๋๋ฌธ์ useRecoilState
๋ฅผ ์ฌ์ฉํ์ง ์๊ณ useRecoilValue
๋ฅผ ์ฌ์ฉํฉ๋๋ค.
import { useRecoilState, useRecoilValue } from 'recoil';
function FontButton() {
const [fontSize, setFontSize] = useRecoilState(fontSizeState);
const fontSizeLabel = useRecoilValue(fontSizeLabelState);
return (
<>
<div>Current font size: ${fontSizeLabel}</div>
<button onClick={setFontSize(fontSize + 1)} style={{fontSize}}>
Click to Enlarge
</button>
</>
);
}
Last updated
Was this helpful?