본문 바로가기
React

React Recoil 사용하기1

by 집요한 개발자 2021. 12. 20.

React Recoil 공식 문서 주소 : https://recoiljs.org/ko/docs/introduction/getting-started/

 

Recoil 시작하기 | Recoil

React 애플리케이션 생성하기

recoiljs.org

기본 환경세팅이 되있다는 가정하에 시작합니다.

 

리액트 프로젝트를 생성후 App.js(루트 컴포넌트)에 recoil을 임포트해줍니다.

 

recoil을 사용하기위한 준비 단계는 1단계 루트컴포넌트에 recoil을 적용해준다.

import { RecoilRoot } from 'recoil';
import CharacterCounter from './component/CharacterCounter';

import './App.css';


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

export default App;

2단계 atom을 사용해 recoil을 사용할 저장소?를 만들어줍니다.

import { atom } from "recoil";

const textState = atom({
    key: 'textState',
    default: '',
});

export default textState;

textState를 키로 사용하고 기본값은 빈값으로 적용한 atom모습입니다.

 

3단계  다음과 같이 useRecoilState를 사용해 변수에 적용시켜 줍니다.

import { useRecoilState } from "recoil";
import textState from "../atom";

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

export default TextInput;

text 변수에 적용하고 setText를 통해 변수를 변경할수 있습니다.

이때 atom을 변경하면 useRecoilState로 구독한 변수들이 자동으로 리렌더링됩니다.

 

3-1단계 atom을 구독하거나 변경하는 것과 조금 다르게 selector을 사용 할수 있습니다.

import { selector, useRecoilValue } from "recoil";
import textState from "../atom";

const charCountState = selector({
    key: 'charCountState',
    get: ({get}) => {
        const text = get(textState);
        
        return text.length;
    }
})

function CharacterCount() {
    const count = useRecoilValue(charCountState);

    return <>Character Count: {count}</>
}

export default CharacterCount;

selector은 atom이나 selector을 입력으로 받는 순수함수입니다.

입력으로 받은 atom이나 selector가 변경되면 자동으로 리렌더링되며

atom과 마찬가지로 구독할 수 있습니다.

 

useRecoilState : 변수와 그 변수의 설정 함수를 사용할 때 사용합니다.

useRecoilValue : 변수의 값만 받아와서 구독 할 때 사용합니다.

useSetRecoilState : 변수를 설정하는 함수만 사용할 때 사용합니다.

댓글