[React] Recoil 시작하기

Sunki-Kim·2023년 7월 22일
0

React

목록 보기
6/7
post-thumbnail

리액트 상태관리 라이브러리엔 다양한 라이브러리와 방법들이 존재하는데,

일반적인 store형태로 되어 flux패턴을 가지는
다른 라이브러리 (Redux 등)과는 성격이 다른
atom 구조 형태로 이루어진 recoil이 있다.

recoil을 사용하면 atoms (공유 상태)에서 selectors (순수 함수)를 거쳐 React 컴포넌트로 내려가는 data-flow graph를 만들 수 있다. Atoms는 컴포넌트가 구독할 수 있는 상태의 단위다. Selectors는 atoms 상태 값을 동기 또는 비동기 방식을 통해 변환한다.

설치하기

npm install recoil

RecoilRoot 적용 하기

// index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {RecoilRoot} from "recoil";

const root = ReactDOM.createRoot(
    document.getElementById('root') as HTMLElement
);
root.render(
    <RecoilRoot>
        <React.StrictMode>
            <App/>
        </React.StrictMode>
    </RecoilRoot>
);

recoilRoot는 Recoil을 사용하는 컴포넌트에서 감싸줘서 사용을 한다. 일반적으로 App을 감싸는 루트 컴포넌트에서 감싸 사용하기 유리하다.

Atom 사용하기

import React, {useRef, useState, useEffect} from 'react';
import {atom, useRecoilState} from 'recoil'

const ageAtom = atom({
    key: 'atom',
    default: 20
})


const Profile = () => {
    // STATE, REF
    const [age, setAge] = useRecoilState(ageAtom);
    const prevAgeRef = useRef(20)

    // EFFECT
    useEffect(() => {
        prevAgeRef.current= age;
    }, [])

    const prevAge = prevAgeRef.current;
    const text = age === prevAge ? '같음' : age > prevAge ? '늙음' : '젊음';

    return (
        <div>
            <p>{`나이가 ${age} 살은 나이가 ${prevAge} 살보다 ${text}`}</p>
            <button onClick={() => {
                const age = Math.floor(Math.random() * 50 + 1);
                setAge(age)
            }}
            >
                나이변경
            </button>
        </div>
    );
}

export default Profile;

atom은 다음과같이 사용한다.

  • atom으로 고유 키값을 부여해준다.
  • default에 기본적인 상태를 부여한다.
    이후 useRecoilState로 상태를 설정하고 atom을 가져와준다.

atom은 단일 스토어로 구성된거와 달리, store에 종속적이지 않게 구현한다.

소스코드

profile
당신에게 가치있는 Developer가 되고자

0개의 댓글