Recoil 기초

김병화·2022년 12월 15일
0
post-thumbnail

Recoil

상태 관리 라이브러리 for React


설치

npm install recoil

RecoilRoot

recoil state를 사용하는 컴포넌트는 부모 트리 어딘가에 나타나는 RecoilRoot 가 필요하다.
Root 컴포넌트가 RecoilRoot를 넣기에 가장 좋은 장소이다.
( index.js 파일에서 <App />을 감싸줘도 됨 )

// App.js
function App() {
  return (
    <RecoilRoot>
      <ExComponent />
    </RecoilRoot>
  );
}

or

// index.js
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  
  <RecoilRoot>
    <App />
  </RecoilRoot>
);

Atom

src 폴더 내에 recoil 폴더를 생성하고 내부에 atom 파일을 만들어준다.

// src/recoil.cartsList.js
import { atom } from "recoil"

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

useRecoilState

useState 와 같다. 배열의 첫 번째 원소는 상태, 두 번째 원소는 상태를 업데이트하는 함수를 반환한다.

const [cartsList, setCartsList] = useRecoilState(cartsListState);

useRecoilValue

getter 역할을 한다.
state 를 변경할 필요는 없고, 조회만 하고싶은 경우 사용한다.

const cartsList = useRecoilValue(cartsListState);

useSetRecoilState

setter 역할을 한다.
state를 업데이트하는 함수만 필요한 경우 사용한다.

const setCartsList = useSetRecoilState(cartsListState);

useResetRecoilState

state를 Default 값으로 변경시켜준다.

const setCartsList = useResetRecoilState(cartsListState);

Selector

derived state 를 나타낸다.
즉, 원래의 state를 그냥 가져오는 것이 아닌 get 프로퍼티를 통해 state를 가공하여 반환한다.

const getCartsListLength = selector({
  key: 'getCartsListLength', // unique ID (with respect to other atoms/selectors)
  get: ({get}) => {
    const carts = get(cartsListState);

    return carts.length;
  },
});
function getCartsQuantity() {
	const quantity = useRecoilValue(getCartsListLength);
	return(
		<>
			<div> Goods in Carts : {quantity} </div>
		</>
	);
}

참고

https://recoiljs.org/ko/docs/introduction/installation

0개의 댓글