[Recoli] Recoil Docs - Basic

hanseungjune·2023년 4월 16일
0

비전공자의 IT준비

목록 보기
62/68
post-thumbnail

📌 기본 코드

import React from 'react';
import {
  RecoilRoot,
  atom,
  selector,
  useRecoilState,
  useRecoilValue,
} from 'recoil';

const textState = atom({
  key: 'textState', // unique ID (with respect to other atoms/selectors)
  default: '', // default value (aka initial value)
});

const charCountState = selector({
  key: 'charCountState', // unique ID (with respect to other atoms/selectors)
  get: ({get}) => {
    const text = get(textState);

    return text.length;
  },
});

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>
  );
}

function CharacterCount() {
  const count = useRecoilValue(charCountState);
  
  return <>Character Count: {count}</>;
}

function CharacterCounter() {
  return (
    <div>
      <TextInput />
      <CharacterCount />
    </div>
  );
}

function App() {
  return (
    <>
      <RecoilRoot>
        <CharacterCounter />
      </RecoilRoot>
    </>
  );
}

export default App;

해당 화면을 구현하기 위한 코드이다.

useRecoilState 은 useState의 업그레이드 버전이라고 생각하자. 대신 atom({ key:'key', default:'default' }) 가 필요하다.

useRecoilValue 은 useRecoilState의 value만 가져오는 것은 말함

selector는 atom에 있는 상태를 직접 가져와서 데이터를 편집하는 것을 말하는데, 밑의 코드 처럼 key와 get을 통해서 textState라는 atom의 값을 가져와서 바꾸는 식의 상태관리를 의미한다.

const charCountState = selector({
  key: 'charCountState', // unique ID (with respect to other atoms/selectors)
  get: ({get}) => {
    const text = get(textState);
    return text.length;
  },
});

😁 후기

위의 기본적인 것만 생각하고 앞으로 진행해야겠다.

profile
필요하다면 공부하는 개발자, 한승준

0개의 댓글