포스트

프론트 상태 관리 Recoil 사용하기

프론트 상태 관리 Recoil 사용하기

이 글은 Tistory에서 이전된 포스팅입니다. 원본은 여기에서 확인할 수 있습니다.

프론트 상태 관리 뭐로 할까하다가 useState 처럼 쓰이는 것 같은 recoil 발견

1
2
3
4
5
6
7
function App() {
  return (
    <RecoilRoot>
      <CharacterCounter />
    </RecoilRoot>
  );
}

대충 감싸주고

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

state key하고 기본 값 넣어주면

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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>
  );

바로 사용 가능, 아무 생각없이 쓰기에 러닝커브 제로에 가깝다.

1
2
3
4
5
6
7
8
const charCountState = selector({
  key: 'charCountState', // unique ID (with respect to other atoms/selectors)
  get: ({get}) => {
    const text = get(textState);

    return text.length;
  },
});

selector 도 있는데

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const filteredTodoListState = selector({
  key: 'FilteredTodoList',
  get: ({get}) => {
    const filter = get(todoListFilterState);
    const list = get(todoListState);

    switch (filter) {
      case 'Show Completed':
        return list.filter((item) => item.isComplete);
      case 'Show Uncompleted':
        return list.filter((item) => !item.isComplete);
      default:
        return list;
    }
  },
});

이런 식으로 작성하면

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function TodoList() {
  // changed from todoListState to filteredTodoListState
  const todoList = useRecoilValue(filteredTodoListState);

  return (
    <>
      <TodoListStats />
      <TodoListFilters />
      <TodoItemCreator />

      {todoList.map((todoItem) => (
        <TodoItem item={todoItem} key={todoItem.id} />
      ))}
    </>
  );
}

이렇게 쓸 수도 있다.

state 2개로 하나의 결과를 내고 있는데 2개 중 하나만 변경돼도 selector는 다시 실행된다.

selector에서 상태 값 여러개를 요리조리 잘 만지면 component를 가독성 좋게 작성할 수 있어보인다.

참고 자료

https://recoiljs.org/ko/docs/introduction/getting-started/#selector

https://recoiljs.org/docs/basic-tutorial/selectors/

이 기사는 저작권자의 CC BY-NC 4.0 라이센스를 따릅니다.