deno.land / x / jotai@v1.8.4 / docs / guides / resettable.mdx

resettable.mdx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
---title: Resettabledescription: How to use resettable atomsnav: 3.06---
The Jotai core doesn't support resettable atoms.But you can create those with helper functions from `jotai/utils`.
## Primitive resettable atom with atomWithReset / useResetAtom
```jsximport { useAtom } from 'jotai'import { atomWithReset, useResetAtom } from 'jotai/utils'
const todoListAtom = atomWithReset([ { description: 'Add a todo', checked: false },])
const TodoList = () => { const [todoList, setTodoList] = useAtom(todoListAtom) const resetTodoList = useResetAtom(todoListAtom) return ( <> <ul> {todoList.map((todo) => ( <li>{todo.description}</li> ))} </ul> <button onClick={() => setTodoList((l) => [ ...l, { description: `New todo ${new Date().toDateString()}`, checked: false, }, ]) }> Add todo </button> <button onClick={resetTodoList}>Reset</button> </> )}```
### Examples
<CodeSandbox id="w91cq" />## Derived atom with RESET symbol
```jsximport { atom, useAtom } from 'jotai'import { atomWithReset, useResetAtom, RESET } from 'jotai/utils'
const dollarsAtom = atomWithReset(0)const centsAtom = atom( (get) => get(dollarsAtom) * 100, (get, set, newValue: number | typeof RESET) => set(dollarsAtom, newValue === RESET ? newValue : newValue / 100))
const ResetExample = () => { const [dollars] = useAtom(dollarsAtom) const setCents = useUpdateAtom(centsAtom) const resetCents = useResetAtom(centsAtom) return ( <> <h3>Current balance ${dollars}</h3> <button onClick={() => setCents(100)}>Set $1</button> <button onClick={() => setCents(200)}>Set $2</button> <button onClick={resetCents}>Reset</button> </> )}```
### Examples
<CodeSandbox id="41c0s" />
jotai

Version Info

Tagged at
a year ago