새로 시작할 프로젝트에서 어떤 상태관리 라이브러리를 선택할까하다가 관련 방식을 사용해본적 없는 jotai 로 결정했다.
일단... 이해한 부분만 작성해보려한다.
//state.ts
import {atom} from "jotai";
export const newAtom = atom<string>("");
//App.tsx
import {useAtom} from "jotai";
import {newAtom} from "./state.ts";
const App = () => {
const [newAtomValue, setNewAtomValue] = useAtom(newAtom);
//...
};
//App.tsx
import {useAtom} from "jotai";
import {useAtomValue} from "./state.ts";
const App = () => {
const newAtomValue = useAtomValue(newAtom);
//...
};
//App.tsx
import {useAtom} from "jotai";
import {useSetAtom} from "./state.ts";
const App = () => {
const setNewAtomValue = useSetAtom(newAtom);
const handleChange = (value : string) => {
setNewAtomValue(value);
}
//...
};
//state.ts
import {atom} from "jotai";
export const counterIdAtom = atom<string[]>([]);
export const counterAtomFamily = atomFamily(id => atom({ id, value: 0 }));
//App.tsx
import {useAtom} from "jotai";
import {counterAtom, counterAtomFamily} from "./state.ts";
const Counter = ({ id }: { id: string }) => {
const [count, setCount] = useAtom(counterAtomFamily(id));
const onPress = () => {
setCount(prev => ({ ...prev, value: prev.value + 1 }));
};
return <Text onPress={onPress}>{count.value}</Text>;
};
const App = () => {
const [inputValue, setInputValue] = useState<string>('');
const [counterId, setCounterId] = useAtom(counterIdAtom);
return (
<>
<TextInput
onChangeText={e => setInputValue(e)}
/>
<Button
title="enter"
onPress={() => setCounterId(prev => [...prev, inputValue])}
/>
{
counterId.map((id, idx) => {
return (
<Counter id={id} key={idx} />
)
})
}
</>
)
};