deno.land / x / jotai@v1.8.4 / docs / integrations / immer.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
87
88
89
90
91
92
93
94
95
96
97
98
99
---title: Immerdescription: This doc describes `jotai/immer` bundle.nav: 4.01---
## Install
You have to install `immer` to access this bundle and its functions.
```npm install immer# oryarn add immer```
## atomWithImmer
`atomWithImmer` creates a new atom similar to the regular [`atom`](../api/core.mdx#atom) [atom] with a different `writeFunction`. In this bundle, we don't have read-only atoms, because the point of these functions is the immer produce(mutability) function.The signature of writeFunction is `(get, set, update: (draft: Draft<Value>) => void) => void`.
```jsximport { useAtom } from 'jotai'import { atomWithImmer } from 'jotai/immer'
const countAtom = atomWithImmer(0)
const Counter = () => { const [count] = useAtom(countAtom) return <div>count: {count}</div>}
const Controls = () => { const [, setCount] = useAtom(countAtom) // setCount === update : (draft: Draft<Value>) => void const inc = () => setCount((c) => (c = c + 1)) return <button onClick={inc}>+1</button>}```
### Examples
Check this example with atomWithImmer:
<CodeSandbox id="vtp3j" />## withImmer
`withImmer` takes an atom and returns a derived atom, same as `atomWithImmer` it has a different `writeFunction`.
```jsximport { useAtom, atom } from 'jotai'import { withImmer } from 'jotai/immer'
const primitiveAtom = atom(0)const countAtom = withImmer(primitiveAtom)
const Counter = () => { const [count] = useAtom(countAtom) return <div>count: {count}</div>}
const Controls = () => { const [, setCount] = useAtom(countAtom) // setCount === update : (draft: Draft<Value>) => void const inc = () => setCount((c) => (c = c + 1)) return <button onClick={inc}>+1</button>}```
## useImmerAtom
This hook takes an atom and replaces the atom's `writeFunction` with the new immer-like `writeFunction` like the previous helpers.
```jsximport { useAtom } from 'jotai'import { useImmerAtom } from 'jotai/immer'
const primitiveAtom = atom(0)
const Counter = () => { const [count] = useImmerAtom(primitiveAtom) return <div>count: {count}</div>}
const Controls = () => { const [, setCount] = useImmerAtom(primitiveAtom) // setCount === update : (draft: Draft<Value>) => void const inc = () => setCount((c) => (c = c + 1)) return <button onClick={inc}>+1</button>}```
It would be better if you don't use `withImmer` and `atomWithImmer` with `useImmerAtom` because they provide the immer-like `writeFunction` and we don't need to create a new one.
## Codesandbox
<CodeSandbox id="ms9pv" />
jotai

Version Info

Tagged at
a year ago