React

[React] 상태 관리 라이브러리 Jotai

Yujzu 2023. 12. 26. 18:28

 

 

# Jotai

: React 상태 관리 라이브러리

 

[ 특징 ]

1.  atom 단위의 상태 관리 : 상태를 개별 원자 단위로 관리

2. 사용이 쉬움 (React Hooks 기반) : Recoil 보다 가벼움

3. 번들 크기가 작음 : 약 1KB

4. 비동기 상태 관리 지원 : async/await, Suspense와 사용 가능

 

# atom

: 독립적인 상태 단위

 

[ 사용 방법 ]

1. 원자(atom) 생성

2. atom을 사용하여 상태 관리

- useAtom을 사용하여 useState 처럼 쉽게 상태를 관리할 수 있다.

import React from 'react';
import { atom, useAtom } from 'jotai';

// 1. atom 생성, initial 값 부여
const countAtom = atom(0);

const Counter = () => {

// 2. atom을 사용하여 컴포넌트에서 상태를 읽고 쓰기 (해당 상태를 변수에 정의해줌)
const [count, setCount] = useAtom(countAtom);

  const increment = () => setCount((prevCount) => prevCount + 1);
  const decrement = () => setCount((prevCount) => prevCount - 1);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
};

// 사용 예시
const App = () => {

// atom의 값을 변경하는 함수를 반환
const setAtomValue = useSetAtom(countAtom); 

  return (
    <div>
      <h1>Jotai Counter</h1>
      <Counter />
    </div>
  );
};

export default App;

 

2. 모달의 위치

// index.html
    <div id="alert"></div>
  // id가 alert인 div를 따로 뺀다.


export const AlertModalPortal = () =>
  createPortal(<AlertModal />, document.getElementById('alert') as HTMLElement);
  // 모달을 렌더링할 외부 DOM 요소로 'alert'라는 ID를 가진 요소를 찾는다. 
  // 외부 요소로부터 분리된 위치에 <AlertModal /> 을 렌더링한다.

 

3. data type

 const showAlertModal = (data: Omit<(typeof alertModalAtom)['init'], 'show'>) => {
    setAtom({ ...data, show: true });
  };

// Omit은 특정 타입에서 지정된 속성을 제외한 새로운 타입을 생성하는 유틸리티 타입
  • typeof alertModalAtom: alertModalAtom이라는 변수 또는 상수에서 타입을 가져옵니다. 보통 Jotai나 Recoil과 같은 상태 관리 라이브러리에서 atom을 생성할 때 사용됩니다.
  • (typeof alertModalAtom)['init']: 이 부분은 alertModalAtom의 속성 중 'init'이라는 특정 속성에 접근합니다. 이 속성은 일반적으로 atom의 초기값을 나타냅니다.
  • Omit<(typeof alertModalAtom)['init'], 'show'>: 'init'이라는 속성에서 'show'라는 속성을 제외한 새로운 타입을 생성합니다.

즉, data라는 변수 또는 매개변수는 alertModalAtom의 초기값('init' 속성)에서 'show'라는 속성을 제외한 타입을 가지도록 정의되었습니다. 이 타입은 'show' 속성을 제외한 나머지 초기값의 타입을 나타냅니다.