Jotai basic

Jayden ·2024년 11월 27일

1. Read write atoms

  • Original atoms을 활용하여 get 함수와 set 함수를 각각 작성할 수 있다.

기본예시


const count = atom(1);
export const readWriteAtom = atom((get) => get(count),
(get, set) => {
    set(count, get(count) + 1);
  },
);

응용예시 : set 함수로 파라미터 전달, 아래 함수에서 newValue 을 활용하여 상태값 업데이트

import { atom } from 'jotai';

const countAtom = atom(0); // 기본 상태 atom
const countWithResetAtom = atom(
  (get) => get(countAtom), // read: countAtom의 현재 값을 반환
  (get, set, newValue) => { // write: countAtom의 값을 업데이트
    if (newValue === 'reset') {
      set(countAtom, 0); // 리셋
    } else {
      set(countAtom, newValue); // 새로운 값으로 업데이트
    }
  }
);

// 사용 예시
function Counter() {
  const [count, setCount] = useAtom(countWithResetAtom);
  return (
    <div>
      <div>Count: {count}</div>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount('reset')}>Reset</button>
    </div>
  );
}

newValue 사용 팁

  • TypeScript를 사용하는 경우, newValue의 타입을 명시적으로 지정하는 것이 좋음.
  • 이를 통해 상태 업데이트 로직에서 타입 안전성을 유지할 수 있음.
const countAtom = atom<number>(0);
const countWithResetAtom = atom<number, 'reset' | number>(
  (get) => get(countAtom),
  (get, set, newValue) => {
    // 타입 안전 보장
  }
);

출처 : https://tutorial.jotai.org/quick-start/

profile
프론트엔드 개발자

0개의 댓글