import { atom } from 'jotai'
const countAtom = atom(0)
const textAtom = atom('hello')
Atom 사용
컴포넌트에서 atom을 사용하려면 useAtom
훅을 사용
→ useState와 구조가 비슷!
import React from 'react'
import { atom, useAtom } from 'jotai'
const countAtom = atom(0)
function Counter() {
const [count, setCount] = useAtom(countAtom)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
</div>
)
}
export default Counter
파생 Atom
jotai는 3가지의 파생 atom을 만들 수 있음
import { atom } from 'jotai';
const priceAtom = atom(10);
const readOnlyAtom = atom((get) => get(priceAtom) * 2);
// const [price] = useAtom(readOnlyAtom);
const writeOnlyAtom = atom(
null,
(get, set, update) => {
set(priceAtom, get(priceAtom) - update.discount)
}
);
// const [, setPrice] = useAtom(writeOnlyAtom);
const readWriteAtom = atom(
(get) => get(priceAtom) * 2,
(get, set, newPrice) => {
set(priceAtom, newPrice / 2)
}
);
// const [price, setPrice] = useAtom(readWriteAtom);
Provider
atom의 값은 React context처럼 컴포넌트 트리상에 저장
Provider를 지정하지 않으면 기본 저장소를 사용하지만, 스코프를 나누고 싶다면 Provider를 활용함
Provider를 활용해 스코프가 나뉘면, 같은 atom을 사용해도 각자의 값을 지닐 수 있음
const ComponentTree = () => (
<>
<Provider>
<Child />
</Provider>
<Provider>
<SecondChild />
</Provider>
</>
)