기업협업으로 출근하게 될 기업이 Recoil 기술스택을 사용 하길래 Recoil 공식문서를 참고하여 개념정리를 미리 하고 출근하려한다.
공식문서: https://recoiljs.org/ko/docs/introduction/getting-started
비교적 간단한 프로젝트엔 무겁게 느껴질 수 있는 Redux와 MobX, 그리고 이들은 근본적으로 React를 위해 출시된 것이 아니다.
React의 hooks와 어울리면서 React에 필요한 것들만 React스럽게 제작한 상태관리 라이브러리 Recoil
Recoil을 사용하면 atoms (공유 상태)에서 selectors (순수 함수)를 거쳐 React 컴포넌트로 내려가는 data-flow graph를 만들 수 있다. Atoms는 컴포넌트가 구독할 수 있는 상태의 단위다. Selectors는 atoms 상태값을 동기 또는 비동기 방식을 통해 변환한다.
Atom은 상태(state)의 일부를 나타낸다. Atoms는 어떤 컴포넌트에서나 읽고 쓸 수 있다. atom의 값을 읽는 컴포넌트들은 암묵적으로 atom을 구독한다. 그래서 atom에 어떤 변화가 있으면 그 atom을 구독하는 모든 컴포넌트들이 재렌더링 되는 결과가 발생한다.
const fontSizeState = atom({ key: 'fontSizeState', default: 14,});
Atoms는 디버깅, 지속성 및 모든 atoms의 map을 볼 수 있는 특정 고급 API에 사용되는 고유한 키가 필요하다. 두개의 atom이 같은 키를 갖는 것은 오류이기 때문에 키값은 전역적으로 고유하도록 해야한다. React 컴포넌트의 상태처럼 기본값도 가진다.
npm add recoil
yarn add recoil
npm or yarn 을 이용하여 recoil 패키지를 설치.
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { RecoilRoot } from "recoil";
ReactDOM.render(
<RecoilRoot>
<App />
</RecoilRoot>,
document.getElementById("root")
);
reocil state를 사용할 컴포넌트라면, RecoilRoot 태그로 감싸주어야 한다.
모든 곳에서 사용할 것이기 때문에 index.js 컴포넌트에 적용시켰다.
const textState = atom({
key: 'textState', // unique ID (with respect to other atoms/selectors)
default: '', // default value a.k.a initial value
})
atom 은 기존의 상태관리 라이브러리에서 쓰이는 store 와 유사한 개념으로, 상태의 단위 이다.
atom이 업데이트 되면, 해당 atom을 구독하고 있던 모든 컴포넌트들의 state가 새로운 값으로 리렌더링 됩니다.
unique 한 id인 key로 구분되는 각 atom은, 여러 컴포넌트에서 atom을 구독하고 있다면 그 컴포넌트들도 똑같은 상태를 공유합니다.
atom, selector는 sre/state/state.js를 만들어 따로 관리해주었다.
import { atom, selector } from "recoil";
export const textState = atom({
key: "textState", // unique ID (with respect to other atoms/selectors)
default: "", // default value (aka initial value)
});
export const charCountState = selector({
key: "charCountState", // unique ID (with respect to other atoms/selectors)
get: ({ get }) => {
const text = get(textState);
return text.length;
},
});
컴포넌트가 atom을 읽고 쓰게 하기 위해서는 useRecoilState()를 아래와 같이 사용하면 된다.
function CharacterCounter (){
return (
<div>
<TextInput />
<CharacterCount />
</div>
);
}
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>
);
}
useRecoilState hook은 atom의 state를 get 그리고 set 할 수 있습니다
const [text, setText] = useRecoilState(textState);
다음과 같이 사용하면, text 는 textState의 value를 가지게 되고(get)
setText는 text의 값을 변경할 수 있습니다!(set)
const charCountState = selector({
key: 'charCountState', // unique ID (with respect to other atoms/selectors)
get: ({get}) => {
const text = get(textState);
return text.length;
},
});
selector 는 derived state, 즉 파생된 state를 나타낼 수 있습니다. 원래의 state를 그냥 가져오는 것이 아닌, get 프로퍼티를 통해 state를 가공하여 반환할 수 있습니다.
useRecoilValue() 훅을 사용해서 charCountState 값을 읽을 수 있다.
function CharacterCount() {
const count = useRecoilValue(charCountState);
return(
<>
<div> Character Count : {count} </div>
</>
);
}
[React] useCallback (0) | 2022.04.21 |
---|---|
[React] 리액트 설계구조를 어떻게 해야하는걸까? (0) | 2022.02.20 |
[React] React Redux (0) | 2021.12.23 |
[React] why use styled component? (0) | 2021.12.17 |
[React] useState 비동기 처리와 함수형 업데이트 (0) | 2021.12.07 |