Skip to content
최진우 edited this page Aug 10, 2021 · 1 revision

Recoil

공식문서, 참고

Recoil 한글 문서 https://recoiljs.org/ko/

소개

React를 위한 상태관리 라이브러리

철학

  1. 작고 React 스러운

    React의 내부상태와 같이 get/set 인터페이스로 사용할 수 있도록 제공

주요 개념

Atoms

상태의 단위

리액트의 state와 유사

Selectors

최소한의 상태를 atoms로 관리하며 그 외는 모두 selectors 순수함수를 통해 계산하여 사용

  • 쓸모없는 상태의 보존을 방지

컴포넌트 입장에선 atoms와 동일한 인터페이스로 동작

예제

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

const fontSizeLabelState = selector({
  key: 'fontSizeLabelState',
  get: ({get}) => {
    const fontSize = get(fontSizeState);
    const unit = 'px';

    return `${fontSize}${unit}`;
  },
});

//

function FontButton() {
  const [fontSize, setFontSize] = useRecoilState(fontSizeState);
  return (
  	<div>
  		<p style={{fontSize}}>font size change</p>
			<button onClick={() => setFontSize((size) => size + 1)} style={{fontSize}}>
	        Click to Enlarge
      </button>
  	</div>
  );
}

function FontButton() {
  const [fontSize, setFontSize] = useRecoilState(fontSizeState);
  const fontSizeLabel = useRecoilValue(fontSizeLabelState);

  return (
    <>
      <div>Current font size: ${fontSizeLabel}</div>

      <button onClick={setFontSize(fontSize + 1)} style={{fontSize}}>
        Click to Enlarge
      </button>
    </>
  );
}

장점

  • React와 유사한 인터페이스
  • selectors에 로직을 분리

단점

  • Recoil 0.4
  • 문서, 커뮤니티
Clone this wiki locally