This repository has been archived by the owner on Jan 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathRecoil_Hooks.js
973 lines (892 loc) · 31.8 KB
/
Recoil_Hooks.js
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+recoil
* @flow strict-local
* @format
*/
'use strict';
import type {Loadable} from '../adt/Recoil_Loadable';
import type {TransactionInterface} from '../core/Recoil_AtomicUpdates';
import type {DefaultValue, PersistenceType} from '../core/Recoil_Node';
import type {RecoilState, RecoilValue} from '../core/Recoil_RecoilValue';
import type {ComponentSubscription} from '../core/Recoil_RecoilValueInterface';
import type {NodeKey, Store, TreeState} from '../core/Recoil_State';
const {atomicUpdater} = require('../core/Recoil_AtomicUpdates');
const {batchUpdates} = require('../core/Recoil_Batching');
const {DEFAULT_VALUE, getNode, nodes} = require('../core/Recoil_Node');
const {
useRecoilMutableSource,
useStoreRef,
} = require('../core/Recoil_RecoilRoot.react');
const {isRecoilValue} = require('../core/Recoil_RecoilValue');
const {
AbstractRecoilValue,
getRecoilValueAsLoadable,
setRecoilValue,
setRecoilValueLoadable,
setUnvalidatedRecoilValue,
subscribeToRecoilValue,
} = require('../core/Recoil_RecoilValueInterface');
const {updateRetainCount} = require('../core/Recoil_Retention');
const {RetentionZone} = require('../core/Recoil_RetentionZone');
const {Snapshot, cloneSnapshot} = require('../core/Recoil_Snapshot');
const {setByAddingToSet} = require('../util/Recoil_CopyOnWrite');
const differenceSets = require('../util/Recoil_differenceSets');
const {isSSR} = require('../util/Recoil_Environment');
const expectationViolation = require('../util/Recoil_expectationViolation');
const filterMap = require('../util/Recoil_filterMap');
const filterSet = require('../util/Recoil_filterSet');
const gkx = require('../util/Recoil_gkx');
const invariant = require('../util/Recoil_invariant');
const mapMap = require('../util/Recoil_mapMap');
const mergeMaps = require('../util/Recoil_mergeMaps');
const {
mutableSourceExists,
useMutableSource,
} = require('../util/Recoil_mutableSource');
const nullthrows = require('../util/Recoil_nullthrows');
const recoverableViolation = require('../util/Recoil_recoverableViolation');
const shallowArrayEqual = require('../util/Recoil_shallowArrayEqual');
const useComponentName = require('../util/Recoil_useComponentName');
const {useCallback, useEffect, useMemo, useRef, useState} = require('react');
// Components that aren't mounted after suspending for this long will be assumed
// to be discarded and their resources released.
const SUSPENSE_TIMEOUT_MS = 120000;
function handleLoadable<T>(
loadable: Loadable<T>,
recoilValue: RecoilValue<T>,
storeRef,
): T {
// We can't just throw the promise we are waiting on to Suspense. If the
// upstream dependencies change it may produce a state in which the component
// can render, but it would still be suspended on a Promise that may never resolve.
if (loadable.state === 'hasValue') {
return loadable.contents;
} else if (loadable.state === 'loading') {
const promise = new Promise(resolve => {
storeRef.current.getState().suspendedComponentResolvers.add(resolve);
});
// $FlowFixMe Flow(prop-missing) for integrating with tools that inspect thrown promises @fb-only
// @fb-only: promise.displayName = `Recoil State: ${recoilValue.key}`;
throw promise;
} else if (loadable.state === 'hasError') {
throw loadable.contents;
} else {
const err = new Error(
`Invalid value of loadable atom "${recoilValue.key}"`,
);
err.stack; // In V8, Error objects keep closures alive until the error.stack property is accessed
throw err;
}
}
function validateRecoilValue(recoilValue, hookName) {
if (!isRecoilValue(recoilValue)) {
throw new Error(
`Invalid argument to ${hookName}: expected an atom or selector but got ${String(
recoilValue,
)}`,
);
}
}
export type SetterOrUpdater<T> = ((T => T) | T) => void;
export type Resetter = () => void;
export type RecoilInterface = {
getRecoilValue: <T>(RecoilValue<T>) => T,
getRecoilValueLoadable: <T>(RecoilValue<T>) => Loadable<T>,
getRecoilState: <T>(RecoilState<T>) => [T, SetterOrUpdater<T>],
getRecoilStateLoadable: <T>(
RecoilState<T>,
) => [Loadable<T>, SetterOrUpdater<T>],
getSetRecoilState: <T>(RecoilState<T>) => SetterOrUpdater<T>,
getResetRecoilState: <T>(RecoilState<T>) => Resetter,
};
/**
* Various things are broken with useRecoilInterface, particularly concurrent mode
* and memory management. They will not be fixed.
* */
function useRecoilInterface_DEPRECATED(): RecoilInterface {
const storeRef = useStoreRef();
const [_, forceUpdate] = useState([]);
const recoilValuesUsed = useRef<$ReadOnlySet<NodeKey>>(new Set());
recoilValuesUsed.current = new Set(); // Track the RecoilValues used just during this render
const previousSubscriptions = useRef<$ReadOnlySet<NodeKey>>(new Set());
const subscriptions = useRef<Map<NodeKey, ComponentSubscription>>(new Map());
const unsubscribeFrom = useCallback(
key => {
const sub = subscriptions.current.get(key);
if (sub) {
sub.release();
subscriptions.current.delete(key);
}
},
[subscriptions],
);
const componentName = useComponentName();
useEffect(() => {
const store = storeRef.current;
function updateState(_state, key) {
if (!subscriptions.current.has(key)) {
return;
}
forceUpdate([]);
}
differenceSets(
recoilValuesUsed.current,
previousSubscriptions.current,
).forEach(key => {
if (subscriptions.current.has(key)) {
expectationViolation(`Double subscription to RecoilValue "${key}"`);
return;
}
const sub = subscribeToRecoilValue(
store,
new AbstractRecoilValue(key),
state => {
updateState(state, key);
},
componentName,
);
subscriptions.current.set(key, sub);
/**
* Since we're subscribing in an effect we need to update to the latest
* value of the atom since it may have changed since we rendered. We can
* go ahead and do that now, unless we're in the middle of a batch --
* in which case we should do it at the end of the batch, due to the
* following edge case: Suppose an atom is updated in another useEffect
* of this same component. Then the following sequence of events occur:
* 1. Atom is updated and subs fired (but we may not be subscribed
* yet depending on order of effects, so we miss this) Updated value
* is now in nextTree, but not currentTree.
* 2. This effect happens. We subscribe and update.
* 3. From the update we re-render and read currentTree, with old value.
* 4. Batcher's effect sets currentTree to nextTree.
* In this sequence we miss the update. To avoid that, add the update
* to queuedComponentCallback if a batch is in progress.
*/
// FIXME delete queuedComponentCallbacks_DEPRECATED when deleting useInterface.
const state = store.getState();
if (state.nextTree) {
store.getState().queuedComponentCallbacks_DEPRECATED.push(() => {
updateState(store.getState(), key);
});
} else {
updateState(store.getState(), key);
}
});
differenceSets(
previousSubscriptions.current,
recoilValuesUsed.current,
).forEach(key => {
unsubscribeFrom(key);
});
previousSubscriptions.current = recoilValuesUsed.current;
});
useEffect(() => {
const subs = subscriptions.current;
return () => subs.forEach((_, key) => unsubscribeFrom(key));
}, [unsubscribeFrom]);
return useMemo(() => {
function useSetRecoilState<T>(
recoilState: RecoilState<T>,
): SetterOrUpdater<T> {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilState, 'useSetRecoilState');
}
return (
newValueOrUpdater: (T => T | DefaultValue) | T | DefaultValue,
) => {
setRecoilValue(storeRef.current, recoilState, newValueOrUpdater);
};
}
function useResetRecoilState<T>(recoilState: RecoilState<T>): Resetter {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilState, 'useResetRecoilState');
}
return () => setRecoilValue(storeRef.current, recoilState, DEFAULT_VALUE);
}
function useRecoilValueLoadable<T>(
recoilValue: RecoilValue<T>,
): Loadable<T> {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilValue, 'useRecoilValueLoadable');
}
if (!recoilValuesUsed.current.has(recoilValue.key)) {
recoilValuesUsed.current = setByAddingToSet(
recoilValuesUsed.current,
recoilValue.key,
);
}
// TODO Restore optimization to memoize lookup
const storeState = storeRef.current.getState();
return getRecoilValueAsLoadable(
storeRef.current,
recoilValue,
gkx('recoil_early_rendering_2021')
? storeState.nextTree ?? storeState.currentTree
: storeState.currentTree,
);
}
function useRecoilValue<T>(recoilValue: RecoilValue<T>): T {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilValue, 'useRecoilValue');
}
const loadable = useRecoilValueLoadable(recoilValue);
return handleLoadable(loadable, recoilValue, storeRef);
}
function useRecoilState<T>(
recoilState: RecoilState<T>,
): [T, SetterOrUpdater<T>] {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilState, 'useRecoilState');
}
return [useRecoilValue(recoilState), useSetRecoilState(recoilState)];
}
function useRecoilStateLoadable<T>(
recoilState: RecoilState<T>,
): [Loadable<T>, SetterOrUpdater<T>] {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilState, 'useRecoilStateLoadable');
}
return [
useRecoilValueLoadable(recoilState),
useSetRecoilState(recoilState),
];
}
return {
getRecoilValue: useRecoilValue,
getRecoilValueLoadable: useRecoilValueLoadable,
getRecoilState: useRecoilState,
getRecoilStateLoadable: useRecoilStateLoadable,
getSetRecoilState: useSetRecoilState,
getResetRecoilState: useResetRecoilState,
};
}, [recoilValuesUsed, storeRef]);
}
const recoilComponentGetRecoilValueCount_FOR_TESTING = {current: 0};
function useRecoilValueLoadable_MUTABLESOURCE<T>(
recoilValue: RecoilValue<T>,
): Loadable<T> {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilValue, 'useRecoilValueLoadable');
}
const storeRef = useStoreRef();
const getLoadable = useCallback(() => {
const store = storeRef.current;
const storeState = store.getState();
const treeState = gkx('recoil_early_rendering_2021')
? storeState.nextTree ?? storeState.currentTree
: storeState.currentTree;
return getRecoilValueAsLoadable(store, recoilValue, treeState);
}, [storeRef, recoilValue]);
const getLoadableWithTesting = useCallback(() => {
if (__DEV__) {
recoilComponentGetRecoilValueCount_FOR_TESTING.current++;
}
return getLoadable();
}, [getLoadable]);
const componentName = useComponentName();
const subscribe = useCallback(
(_storeState, callback) => {
const store = storeRef.current;
const subscription = subscribeToRecoilValue(
store,
recoilValue,
() => {
if (!gkx('recoil_suppress_rerender_in_callback')) {
return callback();
}
// Only re-render if the value has changed.
// This will evaluate the atom/selector now as well as when the
// component renders, but that may help with prefetching.
const newLoadable = getLoadable();
if (!prevLoadableRef.current.is(newLoadable)) {
callback();
}
// If the component is suspended then the effect setting prevLoadableRef
// will not run. So, set the previous value here when its subscription
// is fired to wake it up. We can't just rely on this, though, because
// this only executes when an atom/selector is dirty and the atom/selector
// passed to the hook can dynamically change.
prevLoadableRef.current = newLoadable;
},
componentName,
);
return subscription.release;
},
[storeRef, recoilValue, componentName, getLoadable],
);
const source = useRecoilMutableSource();
const loadable = useMutableSource(source, getLoadableWithTesting, subscribe);
const prevLoadableRef = useRef(loadable);
useEffect(() => {
prevLoadableRef.current = loadable;
});
return loadable;
}
function useRecoilValueLoadable_LEGACY<T>(
recoilValue: RecoilValue<T>,
): Loadable<T> {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilValue, 'useRecoilValueLoadable');
}
const storeRef = useStoreRef();
const [_, forceUpdate] = useState([]);
const componentName = useComponentName();
useEffect(() => {
const store = storeRef.current;
const storeState = store.getState();
const subscription = subscribeToRecoilValue(
store,
recoilValue,
_state => {
if (!gkx('recoil_suppress_rerender_in_callback')) {
return forceUpdate([]);
}
const newLoadable = getRecoilValueAsLoadable(
store,
recoilValue,
store.getState().currentTree,
);
if (!prevLoadableRef.current?.is(newLoadable)) {
forceUpdate(newLoadable);
}
prevLoadableRef.current = newLoadable;
},
componentName,
);
/**
* Since we're subscribing in an effect we need to update to the latest
* value of the atom since it may have changed since we rendered. We can
* go ahead and do that now, unless we're in the middle of a batch --
* in which case we should do it at the end of the batch, due to the
* following edge case: Suppose an atom is updated in another useEffect
* of this same component. Then the following sequence of events occur:
* 1. Atom is updated and subs fired (but we may not be subscribed
* yet depending on order of effects, so we miss this) Updated value
* is now in nextTree, but not currentTree.
* 2. This effect happens. We subscribe and update.
* 3. From the update we re-render and read currentTree, with old value.
* 4. Batcher's effect sets currentTree to nextTree.
* In this sequence we miss the update. To avoid that, add the update
* to queuedComponentCallback if a batch is in progress.
*/
if (storeState.nextTree) {
store.getState().queuedComponentCallbacks_DEPRECATED.push(() => {
prevLoadableRef.current = null;
forceUpdate([]);
});
} else {
if (!gkx('recoil_suppress_rerender_in_callback')) {
return forceUpdate([]);
}
const newLoadable = getRecoilValueAsLoadable(
store,
recoilValue,
store.getState().currentTree,
);
if (!prevLoadableRef.current?.is(newLoadable)) {
forceUpdate(newLoadable);
}
prevLoadableRef.current = newLoadable;
}
return subscription.release;
}, [componentName, recoilValue, storeRef]);
const loadable = getRecoilValueAsLoadable(storeRef.current, recoilValue);
const prevLoadableRef = useRef(loadable);
useEffect(() => {
prevLoadableRef.current = loadable;
});
return loadable;
}
/**
Like useRecoilValue(), but either returns the value if available or
just undefined if not available for any reason, such as pending or error.
*/
function useRecoilValueLoadable<T>(recoilValue: RecoilValue<T>): Loadable<T> {
if (gkx('recoil_memory_managament_2020')) {
// eslint-disable-next-line fb-www/react-hooks
useRetain(recoilValue);
}
if (mutableSourceExists()) {
// eslint-disable-next-line fb-www/react-hooks
return useRecoilValueLoadable_MUTABLESOURCE(recoilValue);
} else {
// eslint-disable-next-line fb-www/react-hooks
return useRecoilValueLoadable_LEGACY(recoilValue);
}
}
/**
Returns the value represented by the RecoilValue.
If the value is pending, it will throw a Promise to suspend the component,
if the value is an error it will throw it for the nearest React error boundary.
This will also subscribe the component for any updates in the value.
*/
function useRecoilValue<T>(recoilValue: RecoilValue<T>): T {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilValue, 'useRecoilValue');
}
const storeRef = useStoreRef();
const loadable = useRecoilValueLoadable(recoilValue);
return handleLoadable(loadable, recoilValue, storeRef);
}
/**
Returns a function that allows the value of a RecoilState to be updated, but does
not subscribe the component to changes to that RecoilState.
*/
function useSetRecoilState<T>(recoilState: RecoilState<T>): SetterOrUpdater<T> {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilState, 'useSetRecoilState');
}
const storeRef = useStoreRef();
return useCallback(
(newValueOrUpdater: (T => T | DefaultValue) | T | DefaultValue) => {
setRecoilValue(storeRef.current, recoilState, newValueOrUpdater);
},
[storeRef, recoilState],
);
}
/**
Returns a function that will reset the value of a RecoilState to its default
*/
function useResetRecoilState<T>(recoilState: RecoilState<T>): Resetter {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilState, 'useResetRecoilState');
}
const storeRef = useStoreRef();
return useCallback(() => {
setRecoilValue(storeRef.current, recoilState, DEFAULT_VALUE);
}, [storeRef, recoilState]);
}
/**
Equivalent to useState(). Allows the value of the RecoilState to be read and written.
Subsequent updates to the RecoilState will cause the component to re-render. If the
RecoilState is pending, this will suspend the component and initiate the
retrieval of the value. If evaluating the RecoilState resulted in an error, this will
throw the error so that the nearest React error boundary can catch it.
*/
function useRecoilState<T>(
recoilState: RecoilState<T>,
): [T, SetterOrUpdater<T>] {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilState, 'useRecoilState');
}
return [useRecoilValue(recoilState), useSetRecoilState(recoilState)];
}
/**
Like useRecoilState(), but does not cause Suspense or React error handling. Returns
an object that indicates whether the RecoilState is available, pending, or
unavailable due to an error.
*/
function useRecoilStateLoadable<T>(
recoilState: RecoilState<T>,
): [Loadable<T>, SetterOrUpdater<T>] {
if (__DEV__) {
// $FlowFixMe[escaped-generic]
validateRecoilValue(recoilState, 'useRecoilStateLoadable');
}
return [useRecoilValueLoadable(recoilState), useSetRecoilState(recoilState)];
}
function useTransactionSubscription(callback: Store => void) {
const storeRef = useStoreRef();
useEffect(() => {
const sub = storeRef.current.subscribeToTransactions(callback);
return sub.release;
}, [callback, storeRef]);
}
function externallyVisibleAtomValuesInState(
state: TreeState,
): Map<NodeKey, mixed> {
const atomValues = state.atomValues.toMap();
const persistedAtomContentsValues = mapMap(
filterMap(atomValues, (v, k) => {
const node = getNode(k);
const persistence = node.persistence_UNSTABLE;
return (
persistence != null &&
persistence.type !== 'none' &&
v.state === 'hasValue'
);
}),
v => v.contents,
);
// Merge in nonvalidated atoms; we may not have defs for them but they will
// all have persistence on or they wouldn't be there in the first place.
return mergeMaps(
state.nonvalidatedAtoms.toMap(),
persistedAtomContentsValues,
);
}
type ExternallyVisibleAtomInfo = {
persistence_UNSTABLE: {
type: PersistenceType,
backButton: boolean,
...
},
...
};
/**
Calls the given callback after any atoms have been modified and the consequent
component re-renders have been committed. This is intended for persisting
the values of the atoms to storage. The stored values can then be restored
using the useSetUnvalidatedAtomValues hook.
The callback receives the following info:
atomValues: The current value of every atom that is both persistable (persistence
type not set to 'none') and whose value is available (not in an
error or loading state).
previousAtomValues: The value of every persistable and available atom before
the transaction began.
atomInfo: A map containing the persistence settings for each atom. Every key
that exists in atomValues will also exist in atomInfo.
modifiedAtoms: The set of atoms that were written to during the transaction.
transactionMetadata: Arbitrary information that was added via the
useSetUnvalidatedAtomValues hook. Useful for ignoring the useSetUnvalidatedAtomValues
transaction, to avoid loops.
*/
function useTransactionObservation_DEPRECATED(
callback: ({
atomValues: Map<NodeKey, mixed>,
previousAtomValues: Map<NodeKey, mixed>,
atomInfo: Map<NodeKey, ExternallyVisibleAtomInfo>,
modifiedAtoms: $ReadOnlySet<NodeKey>,
transactionMetadata: {[NodeKey]: mixed, ...},
}) => void,
) {
useTransactionSubscription(
useCallback(
store => {
let previousTree = store.getState().previousTree;
const currentTree = store.getState().currentTree;
if (!previousTree) {
recoverableViolation(
'Transaction subscribers notified without a previous tree being present -- this is a bug in Recoil',
'recoil',
);
previousTree = store.getState().currentTree; // attempt to trundle on
}
const atomValues = externallyVisibleAtomValuesInState(currentTree);
const previousAtomValues = externallyVisibleAtomValuesInState(
previousTree,
);
const atomInfo = mapMap(nodes, node => ({
persistence_UNSTABLE: {
type: node.persistence_UNSTABLE?.type ?? 'none',
backButton: node.persistence_UNSTABLE?.backButton ?? false,
},
}));
// Filter on existance in atomValues so that externally-visible rules
// are also applied to modified atoms (specifically exclude selectors):
const modifiedAtoms = filterSet(
currentTree.dirtyAtoms,
k => atomValues.has(k) || previousAtomValues.has(k),
);
callback({
atomValues,
previousAtomValues,
atomInfo,
modifiedAtoms,
transactionMetadata: {...currentTree.transactionMetadata},
});
},
[callback],
),
);
}
function useRecoilTransactionObserver(
callback: ({
snapshot: Snapshot,
previousSnapshot: Snapshot,
}) => void,
) {
useTransactionSubscription(
useCallback(
store => {
const snapshot = cloneSnapshot(store, 'current');
const previousSnapshot = cloneSnapshot(store, 'previous');
callback({
snapshot,
previousSnapshot,
});
},
[callback],
),
);
}
function usePrevious<T>(value: T): T | void {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
// Return a snapshot of the current state and subscribe to all state changes
function useRecoilSnapshot(): Snapshot {
const storeRef = useStoreRef();
const [snapshot, setSnapshot] = useState(() =>
cloneSnapshot(storeRef.current),
);
const previousSnapshot = usePrevious(snapshot);
const timeoutID = useRef();
useEffect(() => {
if (timeoutID.current && !isSSR) {
window.clearTimeout(timeoutID.current);
}
return snapshot.retain();
}, [snapshot]);
useTransactionSubscription(
useCallback(store => setSnapshot(cloneSnapshot(store)), []),
);
if (previousSnapshot !== snapshot && !isSSR) {
if (timeoutID.current) {
previousSnapshot?.release_INTERNAL();
window.clearTimeout(timeoutID.current);
}
snapshot.retain();
timeoutID.current = window.setTimeout(() => {
snapshot.release_INTERNAL();
timeoutID.current = null;
}, SUSPENSE_TIMEOUT_MS);
}
return snapshot;
}
function useGotoRecoilSnapshot(): Snapshot => void {
const storeRef = useStoreRef();
return useCallback(
(snapshot: Snapshot) => {
const storeState = storeRef.current.getState();
const prev = storeState.nextTree ?? storeState.currentTree;
const next = snapshot.getStore_INTERNAL().getState().currentTree;
batchUpdates(() => {
const keysToUpdate = new Set();
for (const keys of [prev.atomValues.keys(), next.atomValues.keys()]) {
for (const key of keys) {
if (
prev.atomValues.get(key)?.contents !==
next.atomValues.get(key)?.contents &&
getNode(key).shouldRestoreFromSnapshots
) {
keysToUpdate.add(key);
}
}
}
keysToUpdate.forEach(key => {
setRecoilValueLoadable(
storeRef.current,
new AbstractRecoilValue(key),
next.atomValues.has(key)
? nullthrows(next.atomValues.get(key))
: DEFAULT_VALUE,
);
});
storeRef.current.replaceState(state => {
return {
...state,
stateID: snapshot.getID_INTERNAL(),
};
});
});
},
[storeRef],
);
}
function useSetUnvalidatedAtomValues(): (
values: Map<NodeKey, mixed>,
transactionMetadata?: {...},
) => void {
const storeRef = useStoreRef();
return (values: Map<NodeKey, mixed>, transactionMetadata: {...} = {}) => {
batchUpdates(() => {
storeRef.current.addTransactionMetadata(transactionMetadata);
values.forEach((value, key) =>
setUnvalidatedRecoilValue(
storeRef.current,
new AbstractRecoilValue(key),
value,
),
);
});
};
}
export type RecoilCallbackInterface = $ReadOnly<{
set: <T>(RecoilState<T>, (T => T) | T) => void,
reset: <T>(RecoilState<T>) => void,
snapshot: Snapshot,
gotoSnapshot: Snapshot => void,
transact_UNSTABLE: ((TransactionInterface) => void) => void,
}>;
class Sentinel {}
const SENTINEL = new Sentinel();
function useRecoilCallback<Args: $ReadOnlyArray<mixed>, Return>(
fn: RecoilCallbackInterface => (...Args) => Return,
deps?: $ReadOnlyArray<mixed>,
): (...Args) => Return {
const storeRef = useStoreRef();
const gotoSnapshot = useGotoRecoilSnapshot();
return useCallback(
(...args): Return => {
function set<T>(
recoilState: RecoilState<T>,
newValueOrUpdater: (T => T) | T,
) {
setRecoilValue(storeRef.current, recoilState, newValueOrUpdater);
}
function reset<T>(recoilState: RecoilState<T>) {
setRecoilValue(storeRef.current, recoilState, DEFAULT_VALUE);
}
// Use currentTree for the snapshot to show the currently committed state
const snapshot = cloneSnapshot(storeRef.current); // FIXME massive gains from doing this lazily
const atomicUpdate = atomicUpdater(storeRef.current);
let ret = SENTINEL;
batchUpdates(() => {
const errMsg =
'useRecoilCallback expects a function that returns a function: ' +
'it accepts a function of the type (RecoilInterface) => T = R ' +
'and returns a callback function T => R, where RecoilInterface is an ' +
'object {snapshot, set, ...} and T and R are the argument and return ' +
'types of the callback you want to create. Please see the docs ' +
'at recoiljs.org for details.';
if (typeof fn !== 'function') {
throw new Error(errMsg);
}
// flowlint-next-line unclear-type:off
const cb = (fn: any)({
set,
reset,
snapshot,
gotoSnapshot,
transact_UNSTABLE: atomicUpdate,
});
if (typeof cb !== 'function') {
throw new Error(errMsg);
}
ret = cb(...args);
});
invariant(
!(ret instanceof Sentinel),
'batchUpdates should return immediately',
);
return (ret: Return);
},
deps != null ? [...deps, storeRef] : undefined, // eslint-disable-line fb-www/react-hooks-deps
);
}
// I don't see a way to avoid the any type here because we want to accept readable
// and writable values with any type parameter, but normally with writable ones
// RecoilState<SomeT> is not a subtype of RecoilState<mixed>.
type ToRetain =
| RecoilValue<any> // flowlint-line unclear-type:off
| RetentionZone
| $ReadOnlyArray<RecoilValue<any> | RetentionZone>; // flowlint-line unclear-type:off
function useRetain(toRetain: ToRetain): void {
if (!gkx('recoil_memory_managament_2020')) {
return;
}
// eslint-disable-next-line fb-www/react-hooks
return useRetain_ACTUAL(toRetain);
}
function useRetain_ACTUAL(toRetain: ToRetain): void {
const array = Array.isArray(toRetain) ? toRetain : [toRetain];
const retainables = array.map(a => (a instanceof RetentionZone ? a : a.key));
const storeRef = useStoreRef();
useEffect(() => {
if (!gkx('recoil_memory_managament_2020')) {
return;
}
const store = storeRef.current;
if (timeoutID.current && !isSSR) {
// Already performed a temporary retain on render, simply cancel the release
// of that temporary retain.
window.clearTimeout(timeoutID.current);
timeoutID.current = null;
} else {
for (const r of retainables) {
updateRetainCount(store, r, 1);
}
}
return () => {
for (const r of retainables) {
updateRetainCount(store, r, -1);
}
};
// eslint-disable-next-line fb-www/react-hooks-deps
}, [storeRef, ...retainables]);
// We want to retain if the component suspends. This is terrible but the Suspense
// API affords us no better option. If we suspend and never commit after some
// seconds, then release. The 'actual' retain/release in the effect above
// cancels this.
const timeoutID = useRef();
const previousRetainables = usePrevious(retainables);
if (
!isSSR &&
(previousRetainables === undefined ||
!shallowArrayEqual(previousRetainables, retainables))
) {
const store = storeRef.current;
for (const r of retainables) {
updateRetainCount(store, r, 1);
}
if (previousRetainables) {
for (const r of previousRetainables) {
updateRetainCount(store, r, -1);
}
}
if (timeoutID.current) {
window.clearTimeout(timeoutID.current);
}
timeoutID.current = window.setTimeout(() => {
timeoutID.current = null;
for (const r of retainables) {
updateRetainCount(store, r, -1);
}
}, SUSPENSE_TIMEOUT_MS);
}
}
function useRecoilTransaction<Arguments: $ReadOnlyArray<mixed>>(
fn: TransactionInterface => (...Arguments) => void,
deps?: $ReadOnlyArray<mixed>,
): (...Arguments) => void {
const storeRef = useStoreRef();
return useMemo(
() => (...args: Arguments): void => {
const atomicUpdate = atomicUpdater(storeRef.current);
atomicUpdate(transactionInterface => {
fn(transactionInterface)(...args);
});
},
deps != null ? [...deps, storeRef] : undefined, // eslint-disable-line fb-www/react-hooks-deps
);
}
module.exports = {
recoilComponentGetRecoilValueCount_FOR_TESTING,
useGotoRecoilSnapshot,
useRecoilCallback,
useRecoilInterface: useRecoilInterface_DEPRECATED,
useRecoilSnapshot,
useRecoilState,
useRecoilStateLoadable,
useRecoilTransaction,
useRecoilTransactionObserver,
useRecoilValue,
useRecoilValueLoadable,
useRetain,
useResetRecoilState,
useSetRecoilState,
useSetUnvalidatedAtomValues,
useTransactionObservation_DEPRECATED,
useTransactionSubscription_DEPRECATED: useTransactionSubscription,
};