- 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 사용 팁
const countAtom = atom<number>(0);
const countWithResetAtom = atom<number, 'reset' | number>(
(get) => get(countAtom),
(get, set, newValue) => {
// 타입 안전 보장
}
);