반응형
React에서 상태 관리는 중요한 부분입니다.
기존에 Redux, Context API, Recoil, Zustand 등이 있는데요,
오늘은 이 중에서 Jotai라는 라이브러리를 자세히 알아보겠습니다.
Jotai란?
- Jotai(조타이)는 일본어로 ‘원자(atom)’라는 뜻입니다.
- React에서 상태를 ‘작고 독립적인 단위’인 atom으로 관리하는 가벼운 상태 관리 라이브러리입니다.
- 복잡한 설정 없이도 간단하게 상태를 만들고 사용할 수 있어서 배우기 쉽고, 사용법도 직관적입니다.
Jotai 설치하기
npm install jotai
Jotai 핵심 개념: atom
atom은 상태의 최소 단위입니다.
기본값을 주고 useAtom 훅으로 상태를 읽고 변경합니다.
import { atom, useAtom } from 'jotai';
const countAtom = atom(0); // count라는 이름의 atom 생성, 기본값 0
function Counter() {
const [count, setCount] = useAtom(countAtom);
return (
<div>
<h1>카운트: {count}</h1>
<button onClick={() => setCount(c => c + 1)}>증가</button>
<button onClick={() => setCount(c => c - 1)}>감소</button>
</div>
);
}
- atom(초기값) 으로 상태 생성
- useAtom(해당 atom)으로 상태와 변경 함수 가져오기
- setCount는 직접 값을 넣거나 이전 값을 기반으로 업데이트 가능
여러 atom 만들기 & 조합하기
const firstNameAtom = atom('김');
const lastNameAtom = atom('철수');
const fullNameAtom = atom(
(get) => `${get(firstNameAtom)} ${get(lastNameAtom)}` // firstName과 lastName을 조합
);
function FullName() {
const [fullName] = useAtom(fullNameAtom);
return <div>이름: {fullName}</div>;
}
비동기 상태 관리 (async atom)
Jotai는 atom 안에 async 함수를 넣으면 자동으로 비동기 상태를 관리합니다.
const userAtom = atom(async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/users/1');
if (!res.ok) throw new Error('유저 데이터를 불러오는데 실패했습니다.');
return res.json();
});
function User() {
const [user, setUser] = useAtom(userAtom);
if (!user) return <div>로딩 중...</div>;
return <div>사용자 이름: {user.name}</div>;
}
- atom(async () => {}) 로 비동기 데이터를 불러오고 관리
- 로딩 중일 때는 undefined 또는 null 값이 들어가며 UI에서 처리 가능
- 에러 처리는 try/catch 또는 React Suspense로 가능
반응형
'React' 카테고리의 다른 글
React에서의 Fetching 전략 – React Query, SWR, Axios (0) | 2025.05.27 |
---|---|
React Context API 사용 전략 (0) | 2025.05.27 |
Zustand로 상태 관리하기 (1) | 2025.05.24 |
Recoil로 간단하게 전역 상태 관리하기 (0) | 2025.05.24 |
React에서 이미지 업로드 전 미리보기 구현하기 (0) | 2025.05.19 |