[Recoil] atom , selector 간단하게 정리

승미니·2022년 6월 22일
1

Recoil

목록 보기
1/2
recoil 시작하기 참고
https://recoiljs.org/ko/docs/introduction/getting-started

1. Atom

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

1-1. 사용

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

key는 고유값으로 설정
default는 초기값 이라고 보면 된다.

import { textState } from '../state';
import { useRecoilState } from 'recoil';

cosnt TextInput = () => {
  const [text, setText] = useRecoilState(textState);

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

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

useRecoilState를 이용하여 state를 전역으로 받아올 수 있고 변경도 할 수 있다.

2. Selector

Selector는 파생된 상태(derived state) 의 일부를 나타낸다.
파생된 상태는 상태의 변화다.
파생된 상태를 어떤 방법으로든 주어진 상태를 수정하는 순수 함수에 전달된 상태의 결과물로 생각할 수 있다.

2-1. 특징

  • 캐싱 기능이 있다!!!
  • 순수함수
  • read only
  • 필터링 할 수 있다 -> 근데 쓸 일 잘 없을듯..? 백엔드랑도 맞춰봐야하는 부분이지 않을까...?🤔

2-2. 사용

const charCountState = selector({
  key: 'charCountState', 
  get: ({get}) => {
    const text = get(textState);

    return text.length;
  },
});
profile
Web Frontend Developer

0개의 댓글