npm i jotai
Atom 생성하기 : jotai 에서는 상태를 나타내는 원자(atom)을 사용해 상태를 정의한다. 각각의 원자는 읽기 및 쓰기가 가능한 상태를 나타낸다. 원자를 생성하려면 atom() 함수를 사용함.
EX
import { atom } from 'jotai';
const countAtom = atom(0); // 초기값 0을 가지는 countAtom 생성
const countryAtom = atom('Japan')
const citiesAtom = atom(['Tokyo', 'Kyoto', 'Osaka'])
const animeAtom = atom([
{
title: 'Ghost in the Shell',
year: 1995,
watched: true
},
{
title: 'Serial Experiments Lain',
year: 1998,
watched: false
}
])
Atom 사용하기 : 생성된 원자를 React 컴포넌트에서 사용할 수 있다. useAtom() 훅을 사용해 원자를 읽고 쓸 수 있다.
EX
import { useAtom } from 'jotai';
function Counter() {
const [count, setCount] = useAtom(countAtom);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
상태 갱신하기 : useAtom() 훅에서 반환된 setCount 함수를 사용해 상태를 갱신할 수 있다. 이 함수에 새로운 상태 값을 전달해 상태를 변경할 수 있다.
상태 읽기 : useAtom() 훅에서 반환된 배열의 첫 번째 요소는 현재 상태 값이며, 두 번째 요소는 상태를 갱신하는 함수다. 이를 통해 상태를 읽고 쓸 수 있다.
Atom 조합하기 : jotai 는 여러 원자를 조합해 더 복잡한 상태를 만들 수 있다. 예를 들어 두 개의 원자를 더하여 새로운 원자를 만들 수 있다.
EX
import { atom } from 'jotai';
const count1Atom = atom(0);
const count2Atom = atom(0);
const totalAtom = atom((get) => get(count1Atom) + get(count2Atom));
jotai의 useAtom() 훅에서 제공되는 함수. useAtom() 훅은 배열 구조 분해를 사용해 사용자 정의 원자의 상태와 상태를 업데이트 하는 함수를 반환한다.
jotai 에서 원자의 현재 상태를 얻기 위해서는 get 함수를 사용함. get 함수는 매개변수로 읽고자 하는 원자를 전달받아 해당 원자의 상태를 반환한다. 즉 get(textAtom) 은 textAtom의 현재 값을 반환한다.
EX
const textAtom = atom('hello')
const textLenAtom = atom((get) => get(textAtom).length)
const uppercaseAtom = atom((get) => get(textAtom).toUpperCase())
import { atom } from 'jotai';
// 테마 원자
const themeAtom = atom('light');
// 테마 변경 버튼을 클릭할 때 실행되는 함수
const toggleTheme = () => {
themeAtom.update(theme => theme === 'light' ? 'dark' : 'light');
};
import { atom } from 'jotai';
// 인증 상태 원자
const isAuthenticatedAtom = atom(false);
// 로그인 함수
const login = () => {
isAuthenticatedAtom.set(true);
};
// 로그아웃 함수
const logout = () => {
isAuthenticatedAtom.set(false);
};
import { atom } from 'jotai';
// 현재 페이지 상태 원자
const currentPageAtom = atom('home');
// 페이지 변경 함수
const navigateToPage = (pageName) => {
currentPageAtom.set(pageName);
};
import { Provider, atom, useAtom } from 'jotai'
const textAtom = atom('hello')
const textLenAtom = atom((get) => get(textAtom).length)
const uppercaseAtom = atom((get) => get(textAtom).toUpperCase())
const Input = () => {
//useAtom 훅을 사용해 textAtom 이라는 jotai 원자의 상태를 읽어옴
//text 는 현재 textAtom 의 상태를 가리키는 변수
//setText는 text의 상태를 업데이트하기 위한 함수. 이 함수를 호출하면 해당 상태가 변경됨
const [text, setText] = useAtom(textAtom)
//input 요소를 렌더링
//value 속성에는 text 변수를 할당해 입력 필드의 현재 값이 textAtom의 상태 값과 동기화되게 함
//onChange 이벤트 핸들러는 입력 필드에 사용자가 텍스트를 입력할 때 마다 호출된다
//이 때 입력된 값은 이벤트 객체 'e'의 'target.value'를 통해 가져온다
//그리고 setText() 함수를 사용해 textAtom 의 상태를 이 값으로 업데이트함
return <input value={text} onChange={(e) => setText(e.target.value)} />
}
const CharCount = () => {
const [len] = useAtom(textLenAtom)
return <div>Length: {len}</div>
}
const Uppercase = () => {
const [uppercase] = useAtom(uppercaseAtom)
return <div>Uppercase: {uppercase}</div>
}
const App = () => (
<Provider>
<Input />
<CharCount />
<Uppercase />
</Provider>
)
export default App
참고 :