Atom
in Frontend / Jotai
Jotai Guides
- atom() 함수로 만드는 atom은 사실 immutable object (aka atom config)임
- 실제 값은 exists in store, not in the config object itself
derived atoms (
read()
,write()?
)get
(in read) : reactive, read dep trackedget
(in write) : not tracked! v1 의 unresolved async val 못 읽어옴set
(in write) : target atom 의 Write 함수 불러올 것
예시로 쓸 atom:
atom
const priceAtom = atom(10);
read-only atom:
const readOnlyAtom = atom((get) => get(priceAtom) * 2);
write-only atom
const writeOnlyAtom = atom( null, // CONVENTION임 => ???? (get, set, update) => { set(priceAtom, get(priceAtom) - update.discount); // choice 1 set(priceAtom, (price) => price - update.discount); // choice 2 } );
- 코드 설명
update
is any single value we receive for updating this atom- 아니면 Choice 2 처럼 두번쨰 인자로 함수 가능 (해당 함수의 첫 인자는 이 atom의 현재값!)
- 코드 설명
read-write atom
const readWriteAtom = atom( (get) => get(priceAtom) * 2, (get, set, newPrice) => { set(priceAtom, newPrice / 2); } );
- 한번에 원하는 만큼 여러 atom set 가능함
creation in render functions:
useMemo
또는useRef
필수- for stable reference, referential equality ! . dynamically 하게 생성가능..
- 둘 중 뭐로 감싸야 할지 모를 때는 그냥
useMemo
ㄱㄱ (oruseAtom
때 무한루프)
Signatures
// primitive atom
function atom<Value>(initialValue: Value): PrimitiveAtom<Value>
// read-only atom
function atom<Value>(read: (get: Getter) => Value): Atom<Value>
// writable derived atom
function atom<Value, Args extends unknown[], Result>(
read: (get: Getter) => Value,
write: (get: Getter, set: Setter, ...args: Args) => Result,
): WritableAtom<Value, Args, Result>
// write-only derived atom
function atom<Value, Args extends unknown[], Result>(
read: Value,
write: (get: Getter, set: Setter, ...args: Args) => Result,
): WritableAtom<Value, Args, Result>
derived atoms example
const primitiveAtom = atom(initialValue);
const derivedAtomWithRead = atom(read); // read: (get: Getter) => Value
const derivedAtomWithReadWrite = atom(read, write);
// write : (get: Getter, set: Setter, ...args: Args ) => Result
const derivedAtomWithWriteOnly = atom(null, write); // function
2 types of atoms:
- writable atoms (primitive (setState의 것과 같음), dervied 중 write 가 있는)
- read-only atom
- 그 외:
debug label
,onMount
,signal