본문 바로가기
front-end/React

[React]'Recoil' 상태관리 라이브러리 사용하기

by -제이리 2022. 4. 21.
728x90
320x100

공식문서: https://recoiljs.org/ko/docs/introduction/installation

 

1. 설치하기 

//npm 설치
npm install recoil 

//yarn 설치
yarn add recoil

 

2.사용방법 (예제-Character Counter 만들기)

(1) RecoilRoot: ​부모트리에 <RecoilRoot> 로 감싸준다

//App.js

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

function App() {
  return (
    <RecoilRoot>  //->감싸주기
      <CharacterCounter />
    </RecoilRoot>
  );
}

 

(2). Atom

Atom 상태(state)의 단위를 나타낸다. Atoms는 어떤 컴포넌트에서나 읽고 쓸 수 있다. atom의 값을 읽는 컴포넌트들은 암묵적으로 atom을 구독한다. 그래서 atom에 어떤 변화(업데이트)가 있으면 그 atom을 구독하는 모든 컴포넌트들이 재 렌더링 되는 결과(상태를 동일하게 공유)가 발생할 것이다.

 

(1) Atom 으로 상태만들기

//Atom.js
import { atom } from "recoil";

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

(2) atom 읽고 쓰기

import { textState } from './Atoms';

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

//Another component
function TextInput() {
  const [text, setText] = useRecoilState(textState); //->useState 대신 useReCoilState로 상태관리

  const onChange = (event) => {
    setText(event.target.value);
  };

  return (
    <div>
      <input type="text" value={text} onChange={onChange} />
      <br />
      Echo: {text}
    </div>
  );
}

 

(3)Selector

Selector는 다른 Atom들 혹은 Selector들을 받아 사용하는 순수 함수이다.

Atom 이나 Selector들 중 업데이트 되는것이 있다면 Selector함수는 다시 평가(re-evaluate)된다. 다시 평가될때 컴포넌트는 리렌더 된다.

// Atom.js

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

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

    return text.length;
  },
});

우리는 useRecoilValue() 훅을 사용해서 charCountState 값을 읽을 수 있다.

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

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

 

예제 결과물


 

728x90
320x100

'front-end > React' 카테고리의 다른 글

[React] 천단위마다 쉼표 넣는 방법  (0) 2022.05.23
[React] Fragments 란?  (0) 2022.05.22
[React] nanoid 나노아이디  (0) 2022.05.21
[React] react-scroll-motion 사용하기  (0) 2022.05.04
React 설치 및 기타설치 모음  (0) 2022.04.01

댓글