jotai

PromptAction·2024년 5월 8일

백엔드

목록 보기
18/20

jotai

  • React의 상태 관리 라이브러리 중 하나.
  • React 애플리케이션에서 상태를 관리하기 위해 사용된다
  • 간단하고 직관적인 API를 제공하여 React 상태를 선언적이고 효율적으로 관리할 수 있게 해줌
  • useState 훅과 유사한 개념

설치

npm i jotai

Atom

  • Atom 생성하기 : jotai 에서는 상태를 나타내는 원자(atom)을 사용해 상태를 정의한다. 각각의 원자는 읽기 및 쓰기가 가능한 상태를 나타낸다. 원자를 생성하려면 atom() 함수를 사용함.

  • EX

import { atom } from 'jotai';

const countAtom = atom(0); // 초기값 0을 가지는 countAtom 생성

const countryAtom = atom('Japan')

const citiesAtom = atom(['Tokyo', 'Kyoto', 'Osaka'])

const animeAtom = atom([
  {
    title: 'Ghost in the Shell',
    year: 1995,
    watched: true
  },
  {
    title: 'Serial Experiments Lain',
    year: 1998,
    watched: false
  }
])
  • Atom 사용하기 : 생성된 원자를 React 컴포넌트에서 사용할 수 있다. useAtom() 훅을 사용해 원자를 읽고 쓸 수 있다.

  • EX

import { useAtom } from 'jotai';

function Counter() {
  const [count, setCount] = useAtom(countAtom);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
  • 상태 갱신하기 : useAtom() 훅에서 반환된 setCount 함수를 사용해 상태를 갱신할 수 있다. 이 함수에 새로운 상태 값을 전달해 상태를 변경할 수 있다.

  • 상태 읽기 : useAtom() 훅에서 반환된 배열의 첫 번째 요소는 현재 상태 값이며, 두 번째 요소는 상태를 갱신하는 함수다. 이를 통해 상태를 읽고 쓸 수 있다.

  • Atom 조합하기 : jotai 는 여러 원자를 조합해 더 복잡한 상태를 만들 수 있다. 예를 들어 두 개의 원자를 더하여 새로운 원자를 만들 수 있다.

  • EX

import { atom } from 'jotai';

const count1Atom = atom(0);
const count2Atom = atom(0);

const totalAtom = atom((get) => get(count1Atom) + get(count2Atom));
  • 컴포넌트에서 사용할 때의 최적화 : jotai는 자동으로 컴포넌트를 최적화하여, 상태가 변경될 때 해당 컴포넌트만 다시 렌더링되도록 한다.

GET

  • jotai의 useAtom() 훅에서 제공되는 함수. useAtom() 훅은 배열 구조 분해를 사용해 사용자 정의 원자의 상태와 상태를 업데이트 하는 함수를 반환한다.

  • jotai 에서 원자의 현재 상태를 얻기 위해서는 get 함수를 사용함. get 함수는 매개변수로 읽고자 하는 원자를 전달받아 해당 원자의 상태를 반환한다. 즉 get(textAtom) 은 textAtom의 현재 값을 반환한다.

  • EX

const textAtom = atom('hello')
const textLenAtom = atom((get) => get(textAtom).length)
const uppercaseAtom = atom((get) => get(textAtom).toUpperCase())

jotai EX

  • 테마 관리
import { atom } from 'jotai';

// 테마 원자
const themeAtom = atom('light');

// 테마 변경 버튼을 클릭할 때 실행되는 함수
const toggleTheme = () => {
  themeAtom.update(theme => theme === 'light' ? 'dark' : 'light');
};
  • 인증 상태 관리
import { atom } from 'jotai';

// 인증 상태 원자
const isAuthenticatedAtom = atom(false);

// 로그인 함수
const login = () => {
  isAuthenticatedAtom.set(true);
};

// 로그아웃 함수
const logout = () => {
  isAuthenticatedAtom.set(false);
};
  • 페이지 네비게이션 상태 관리
import { atom } from 'jotai';

// 현재 페이지 상태 원자
const currentPageAtom = atom('home');

// 페이지 변경 함수
const navigateToPage = (pageName) => {
  currentPageAtom.set(pageName);
};
  • 쉬운 텍스트 EX
import { Provider, atom, useAtom } from 'jotai'

const textAtom = atom('hello')
const textLenAtom = atom((get) => get(textAtom).length)
const uppercaseAtom = atom((get) => get(textAtom).toUpperCase())

const Input = () => {
  //useAtom 훅을 사용해 textAtom 이라는 jotai 원자의 상태를 읽어옴
  //text 는 현재 textAtom 의 상태를 가리키는 변수
  //setText는 text의 상태를 업데이트하기 위한 함수. 이 함수를 호출하면 해당 상태가 변경됨
  const [text, setText] = useAtom(textAtom)
  //input 요소를 렌더링
  //value 속성에는 text 변수를 할당해 입력 필드의 현재 값이 textAtom의 상태 값과 동기화되게 함
  //onChange 이벤트 핸들러는 입력 필드에 사용자가 텍스트를 입력할 때 마다 호출된다
  //이 때 입력된 값은 이벤트 객체 'e'의 'target.value'를 통해 가져온다
  //그리고 setText() 함수를 사용해 textAtom 의 상태를 이 값으로 업데이트함
  return <input value={text} onChange={(e) => setText(e.target.value)} />
}

const CharCount = () => {
  const [len] = useAtom(textLenAtom)
  return <div>Length: {len}</div>
}

const Uppercase = () => {
  const [uppercase] = useAtom(uppercaseAtom)
  return <div>Uppercase: {uppercase}</div>
}

const App = () => (
  <Provider>
    <Input />
    <CharCount />
    <Uppercase />
  </Provider>
)

export default App

jotai의 다양한 함수

  • useUpdateAtom(atom: Atom)
    • 원자의 상태를 업데이트 하는 함수를 반환
    • useAtom() 훅과 유사하지만 상태를 읽지 않고 업데이트만 수행
  • useResetAtom(atom: Atom)
    • 원자의 상태를 초기 값으로 재설정하는 함수를 반환
    • 이 함수를 호출하면 원자의 상태가 초기 값으로 다시 설정
  • useMemoizedAtom(atom: Atom)
    • 메모이제이션된 원자를 반환
    • 이 함수를 사용하면 성능을 최적화 할 수 있음
  • splitAtom<S, A extends T>(atom: Atom, splitter: (s: T) => S, merger: (s: S) => T)
    • 원자를 분할하고, 분할 상태를 조작하고, 다시 원래 상태로 합치는 함수를 반환
    • 이 함수를 사용해 복합적인 상태를 분리하여 관리할 수 있음

참고 :

0개의 댓글