Skip to main content

[note] jotai 筆記

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

使用 atomWithResetuseResetAtom 可以把取得一個 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>;
}