deno.land / x / jotai@v1.8.4 / docs / advanced-recipes / atom-creators.mdx

atom-creators.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
---title: Atom creatorsnav: 5.02---
## atomWithToggle
> `atomWithToggle` creates a new atom with a boolean as initial state & a setter function to toggle it.This avoids the boilerplate of having to set up another atom just to update the state of the first.
```tsimport { WritableAtom, atom } from 'jotai'
export function atomWithToggle( initialValue?: boolean): WritableAtom<boolean, boolean | undefined> { const anAtom = atom(initialValue, (get, set, nextValue?: boolean) => { const update = nextValue ?? !get(anAtom) set(anAtom, update) }) return anAtom as WritableAtom<boolean, boolean | undefined>}```
An optional initial state can be provided as the first argument.
The setter function can have an optional argument to force a particular state, such as if you want to make a setActive function out of it.
Here is how it's used.
```jsimport { atomWithToggle } from 'XXX'
// will have an initial value set to trueconst isActiveAtom = atomWithToggle(true)```
And in a component:
```jsxconst Toggle = () => { const [isActive, toggle] = useAtom(isActiveAtom) return ( <> <button onClick={() => toggle()}> isActive: {isActive ? 'yes' : 'no'} </button> <button onClick={() => toggle(true)}>force true</button> <button onClick={() => toggle(false)}>force false</button> </> )}```
## atomWithToggleAndStorage
> `atomWithToggleAndStorage` is like [`atomWithToggle`](#atom-with-toggle) but also persist the state anytime it changes in given storage using [`atomWithStorage`](../api/utils.mdx#atom-with-storage).Here is the source:
```tsimport { WritableAtom, atom } from 'jotai'import { atomWithStorage } from 'jotai/utils'
export function atomWithToggleAndStorage( key: string, initialValue?: boolean, storage?: any): WritableAtom<boolean, boolean | undefined> { const anAtom = atomWithStorage(key, initialValue, storage) const derivedAtom = atom( (get) => get(anAtom), (get, set, nextValue?: boolean) => { const update = nextValue ?? !get(anAtom) set(anAtom, update) } ) return derivedAtom}```
And how it's used:
```jsimport { atomWithToggleAndStorage } from 'XXX'
// will have an initial value set to false & get stored in localStorage under the key "isActive"const isActiveAtom = atomWithToggleAndStorage('isActive')```
The usage in a component is also the same as [`atomWithToggle`](#atom-with-toggle).
## atomWithCompare
> `atomWithCompare` creates atom that triggers updates when custom compare function `areEqual(prev, next)` is false.This can help you avoid unwanted re-renders by ignoring state changes that don't matter to your application.
Note: Jotai uses `Object.is` internally to compare values when changes occur. If `areEqual(a, b)` returns false, but `Object.is(a, b)` returns true, Jotai will not trigger an update.
```tsimport { atomWithReducer } from 'jotai/utils'
export function atomWithCompare<Value>( initialValue: Value, areEqual: (prev: Value, next: Value) => boolean) { return atomWithReducer(initialValue, (prev: Value, next: Value) => { if (areEqual(prev, next)) { return prev } return next })}```
Here's how you'd use it to make an atom that ignores updates that are shallow-equal:
```tsimport { atomWithCompare } from 'XXX'import { shallowEquals } from 'YYY'import { CSSProperties } from 'react'
const styleAtom = atomWithCompare<CSSProperties>( { backgroundColor: 'blue' }, shallowEquals)```
In a component:
```jsxconst StylePreview = () => { const [styles, setStyles] = useAtom(styleAtom) return ( <div> <div styles={styles}>Style preview</div> {/* Clicking this button twice will only trigger one render */} <button onClick={() => setStyles({ ...styles, backgroundColor: 'red' })}> Set background to red </button> {/* Clicking this button twice will only trigger one render */} <button onClick={() => setStyles({ ...styles, fontSize: 32 })}> Enlarge font </button> </div> )}```
## atomWithRefresh
> `atomWithRefresh` creates a derived atom that can be force-refreshed, by using> the update function.This is helpful when you need to refresh asynchronous data after performing aside effect.
It can also be used to implement "pull to refresh" functionality.
```tsimport { atom, Getter } from 'jotai'
export function atomWithRefresh<T>(fn: (get: Getter) => T) { const refreshCounter = atom(0) return atom( (get) => { get(refreshCounter) return fn(get) }, (_, set) => set(refreshCounter, (i) => i + 1) )}```
Here's how you'd use it to implement an refresh-able source of data:
```jsimport { atomWithRefresh } from 'XXX'
const postsAtom = atomWithRefresh((get) => fetch('https://jsonplaceholder.typicode.com/posts').then((r) => r.json()))```
In a component:
```jsxconst PostsList = () => { const [posts, refreshPosts] = useAtom(postsAtom) return ( <div> <ul> {posts.map((post) => ( <li key={post.id}>{post.title}</li> ))} </ul> {/* Clicking this button will re-fetch the posts */} <button type="button" onClick={refreshPosts}> Refresh posts </button> </div> )}```
## atomWithListeners
> `atomWithListeners` creates an atom and a hook. The hook can be called to> add a new listener. The hook takes as an argument a callback, and that> callback is called every time the atom's value is set. The hook also> returns a function to remove the listener.This can be useful when you want to create a component that can listen to whenan atom's state changes without having to re-render that component with each ofthose state changes.
```tsimport { useEffect } from 'react'import { atom, Getter, Setter, SetStateAction } from 'jotai'import { useUpdateAtom } from 'jotai/utils'
type Callback<Value> = ( get: Getter, set: Setter, newVal: Value, prevVal: Value) => void
export function atomWithListeners<Value>(initialValue: Value) { const baseAtom = atom(initialValue) const listenersAtom = atom(<Callback<Value>[]>[]) const anAtom = atom( (get) => get(baseAtom), (get, set, arg: SetStateAction<Value>) => { const prevVal = get(baseAtom) set(baseAtom, arg) const newVal = get(baseAtom) get(listenersAtom).forEach((callback) => { callback(get, set, newVal, prevVal) }) } ) const useListener = (callback: Callback<Value>) => { const setListeners = useUpdateAtom(listenersAtom) useEffect(() => { setListeners((prev) => [...prev, callback]) return () => setListeners((prev) => { const index = prev.indexOf(callback) return [...prev.slice(0, index), ...prev.slice(index + 1)] }) }, [setListeners, callback]) } return [anAtom, useListener] as const}```
In a component:
```jsxconst [countAtom, useCountListener] = atomWithListeners(0)
function EvenCounter() { const [evenCount, setEvenCount] = useState(0) useCountListener( useCallback( (get, set, newVal, prevVal) => { // Every time `countAtom`'s value is set, we check if its new value // is even, and if it is, we increment `evenCount`. if (newVal % 2 === 0) { setEvenCount((c) => c + 1) } }, [setEvenCount] ) ) return <>Count was set to an even number {evenCount} times.</>}```
## atomWithBroadcast
> `atomWithBroadcast` creates an atom. The atom will be shared between> browser tabs and frames, similar to `atomWithStorage` but with the> initialization limitation.This can be useful when you want the state to interact with each other withoutthe use of localStorage and that by just using The Broadcast Channel API allowsbasic communication between browsing contexts (that is, windows, tabs, frames,create a component or iframes) and workers on the same origin. According to the MDN documentation receiving a message in initialization is not supported in broadcast and if we want to support that we may need to add extra stuff to atomWithBroadcast (like local storage).
```tsximport { atom } from 'jotai'
export function atomWithBroadcast<Value>(key: string, initialValue: Value) { const baseAtom = atom(initialValue) const listeners = new Set<(event: MessageEvent<any>) => void>() const channel = new BroadcastChannel(key) channel.onmessage = (event) => { listeners.forEach((l) => l(event)) } const broadcastAtom = atom<Value, { isEvent: boolean; value: Value }>( (get) => get(baseAtom), (get, set, update) => { set(baseAtom, update.value) if (!update.isEvent) { channel.postMessage(get(baseAtom)) } } ) broadcastAtom.onMount = (setAtom) => { const listener = (event: MessageEvent<any>) => { setAtom({ isEvent: true, value: event.data }) } listeners.add(listener) return () => { listeners.delete(listener) } } const returnedAtom = atom<Value, Value>( (get) => get(broadcastAtom), (get, set, update) => { set(broadcastAtom, { isEvent: false, value: update }) } ) return returnedAtom}const broadAtom = atomWithBroadcast('count', 0)
const ListOfThings = () => { const [count, setCount] = useAtom(broadAtom) return ( <div> {count} <button onClick={() => setCount(count + 1)}>+1</button> </div> )}```
<CodeSandbox id="ugkzm0" />## atomWithDebounce
> `atomWithDebounce` helps with creating an atom where state set should be debounced.This util is useful for text search inputs, where you would like to call **functions in derived atoms only once** after waiting for a duration, instead of firing an action on every keystroke.
```tsximport { atom, SetStateAction } from 'jotai'
export default function atomWithDebounce<T>( initialValue: T, delayMilliseconds = 500, shouldDebounceOnReset = false) { const prevTimeoutAtom = atom<ReturnType<typeof setTimeout> | undefined>( undefined ) // DO NOT EXPORT currentValueAtom as using this atom to set state can cause // inconsistent state between currentValueAtom and debouncedValueAtom const _currentValueAtom = atom(initialValue) const isDebouncingAtom = atom(false) const debouncedValueAtom = atom( initialValue, (get, set, update: SetStateAction<T>) => { clearTimeout(get(prevTimeoutAtom)) const prevValue = get(_currentValueAtom) const nextValue = typeof update === 'function' ? (update as (prev: T) => T)(prevValue) : update const onDebounceStart = () => { set(_currentValueAtom, nextValue) set(isDebouncingAtom, true) } const onDebounceEnd = () => { set(debouncedValueAtom, nextValue) set(isDebouncingAtom, false) } onDebounceStart() if (!shouldDebounceOnReset && nextValue === initialValue) { onDebounceEnd() return } const nextTimeoutId = setTimeout(() => { onDebounceEnd() }, delayMilliseconds) // set previous timeout atom in case it needs to get cleared set(prevTimeoutAtom, nextTimeoutId) } ) // exported atom setter to clear timeout if needed const clearTimeoutAtom = atom(null, (get, set, _arg) => { clearTimeout(get(prevTimeoutAtom)) set(isDebouncingAtom, false) }) return { currentValueAtom: atom((get) => get(_currentValueAtom)), isDebouncingAtom, clearTimeoutAtom, debouncedValueAtom, }}```
### Caveat
Please note that this atom has different objectives from concurrent features in React 18 such as `useTransition` and `useDeferredValue` whose main aim is to prevent blocking of interaction with the page for expensive updates.
For more info, please read this github discussion https://github.com/reactwg/react-18/discussions/41 under the section titled **"How is it different from setTimeout?"**
### Example Usage
The sandbox link below shows how we would use a derived atom to fetch state based on the value of `debouncedValueAtom`.
When typing a pokemon's name in `<SearchInput>`, we do not send a get request on every letter, but only after `delayMilliseconds` has passed since the last text input.
This reduces the number of backend requests to the server.
<CodeSandbox id="cjrz2y" />
jotai

Version Info

Tagged at
a year ago