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?