[note] jotai 筆記
- utils @ jot > api
TL;DR
import { atom, useAtom, useAtomValue } from 'jotai';
import { useAtomValue, useUpdateAtom } from 'jotai/utils'
const isEditingAtom = atom(false);
const App = () => {
// normal usage
const [isEditing, setIsEditing] = useAtom(countAtom)
// if only need the setter
// useUpdateAtom can prevent unnecessary re-render
const setIsEditing = useUpdateAtom(isEditingAtom);
// if only need the getter
const isEditing = useAtomValue(isEditingAtom);
}
MISC
Resettable
resettable @ jotai > guides
使用 atomWithReset
和 useResetAtom
可以把取得一個 function 來把 atom 設回 default value:
const todoListAtom = atomWithReset([{ description: 'Add a todo', checked: false }])
const TodoList = () => {
const [todoList, setTodoList] = useAtom(todoListAtom)
const resetTodoList = useResetAtom(todoListAtom)
return <button onClick={resetTodoList}>Reset</button>;
}
Good Discussion
如果想要在 render 時不透過 useEffect 設定 atom 的初始值
Can an atom be initialized on the first render? @ Github Discussion
// https://github.com/pmndrs/jotai/discussions/581#discussioncomment-972361
const fooAtom = atom(null)
const ParentComponent = ({ foo }) => (
<Provider initialValues={[[fooAtom, foo]]}>
<ChildComponent />
</Provider>
)
const ChildComponent = () => {
const [foo, setFoo] = useAtom(fooAtom)
// foo is already initialized.
}