-
Notifications
You must be signed in to change notification settings - Fork 47.2k
/
ExhaustiveDeps.js
1859 lines (1765 loc) · 63 KB
/
ExhaustiveDeps.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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable no-for-of-loops/no-for-of-loops */
'use strict';
export default {
meta: {
type: 'suggestion',
docs: {
description:
'verifies the list of dependencies for Hooks like useEffect and similar',
recommended: true,
url: 'https://github.com/facebook/react/issues/14920',
},
fixable: 'code',
hasSuggestions: true,
schema: [
{
type: 'object',
additionalProperties: false,
enableDangerousAutofixThisMayCauseInfiniteLoops: false,
properties: {
additionalHooks: {
type: 'string',
},
enableDangerousAutofixThisMayCauseInfiniteLoops: {
type: 'boolean',
},
},
},
],
},
create(context) {
// Parse the `additionalHooks` regex.
const additionalHooks =
context.options &&
context.options[0] &&
context.options[0].additionalHooks
? new RegExp(context.options[0].additionalHooks)
: undefined;
const enableDangerousAutofixThisMayCauseInfiniteLoops =
(context.options &&
context.options[0] &&
context.options[0].enableDangerousAutofixThisMayCauseInfiniteLoops) ||
false;
const options = {
additionalHooks,
enableDangerousAutofixThisMayCauseInfiniteLoops,
};
function reportProblem(problem) {
if (enableDangerousAutofixThisMayCauseInfiniteLoops) {
// Used to enable legacy behavior. Dangerous.
// Keep this as an option until major IDEs upgrade (including VSCode FB ESLint extension).
if (Array.isArray(problem.suggest) && problem.suggest.length > 0) {
problem.fix = problem.suggest[0].fix;
}
}
context.report(problem);
}
const scopeManager = context.getSourceCode().scopeManager;
// Should be shared between visitors.
const setStateCallSites = new WeakMap();
const stateVariables = new WeakSet();
const stableKnownValueCache = new WeakMap();
const functionWithoutCapturedValueCache = new WeakMap();
const useEventVariables = new WeakSet();
function memoizeWithWeakMap(fn, map) {
return function(arg) {
if (map.has(arg)) {
// to verify cache hits:
// console.log(arg.name)
return map.get(arg);
}
const result = fn(arg);
map.set(arg, result);
return result;
};
}
/**
* Visitor for both function expressions and arrow function expressions.
*/
function visitFunctionWithDependencies(
node,
declaredDependenciesNode,
reactiveHook,
reactiveHookName,
isEffect,
) {
if (isEffect && node.async) {
reportProblem({
node: node,
message:
`Effect callbacks are synchronous to prevent race conditions. ` +
`Put the async function inside:\n\n` +
'useEffect(() => {\n' +
' async function fetchData() {\n' +
' // You can await here\n' +
' const response = await MyAPI.getData(someId);\n' +
' // ...\n' +
' }\n' +
' fetchData();\n' +
`}, [someId]); // Or [] if effect doesn't need props or state\n\n` +
'Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching',
});
}
// Get the current scope.
const scope = scopeManager.acquire(node);
// Find all our "pure scopes". On every re-render of a component these
// pure scopes may have changes to the variables declared within. So all
// variables used in our reactive hook callback but declared in a pure
// scope need to be listed as dependencies of our reactive hook callback.
//
// According to the rules of React you can't read a mutable value in pure
// scope. We can't enforce this in a lint so we trust that all variables
// declared outside of pure scope are indeed frozen.
const pureScopes = new Set();
let componentScope = null;
{
let currentScope = scope.upper;
while (currentScope) {
pureScopes.add(currentScope);
if (currentScope.type === 'function') {
break;
}
currentScope = currentScope.upper;
}
// If there is no parent function scope then there are no pure scopes.
// The ones we've collected so far are incorrect. So don't continue with
// the lint.
if (!currentScope) {
return;
}
componentScope = currentScope;
}
const isArray = Array.isArray;
// Next we'll define a few helpers that helps us
// tell if some values don't have to be declared as deps.
// Some are known to be stable based on Hook calls.
// const [state, setState] = useState() / React.useState()
// ^^^ true for this reference
// const [state, dispatch] = useReducer() / React.useReducer()
// ^^^ true for this reference
// const ref = useRef()
// ^^^ true for this reference
// const onStuff = useEvent(() => {})
// ^^^ true for this reference
// False for everything else.
function isStableKnownHookValue(resolved) {
if (!isArray(resolved.defs)) {
return false;
}
const def = resolved.defs[0];
if (def == null) {
return false;
}
// Look for `let stuff = ...`
if (def.node.type !== 'VariableDeclarator') {
return false;
}
let init = def.node.init;
if (init == null) {
return false;
}
while (init.type === 'TSAsExpression') {
init = init.expression;
}
// Detect primitive constants
// const foo = 42
let declaration = def.node.parent;
if (declaration == null) {
// This might happen if variable is declared after the callback.
// In that case ESLint won't set up .parent refs.
// So we'll set them up manually.
fastFindReferenceWithParent(componentScope.block, def.node.id);
declaration = def.node.parent;
if (declaration == null) {
return false;
}
}
if (
declaration.kind === 'const' &&
init.type === 'Literal' &&
(typeof init.value === 'string' ||
typeof init.value === 'number' ||
init.value === null)
) {
// Definitely stable
return true;
}
// Detect known Hook calls
// const [_, setState] = useState()
if (init.type !== 'CallExpression') {
return false;
}
let callee = init.callee;
// Step into `= React.something` initializer.
if (
callee.type === 'MemberExpression' &&
callee.object.name === 'React' &&
callee.property != null &&
!callee.computed
) {
callee = callee.property;
}
if (callee.type !== 'Identifier') {
return false;
}
const id = def.node.id;
const {name} = callee;
if (name === 'useRef' && id.type === 'Identifier') {
// useRef() return value is stable.
return true;
} else if (isUseEventIdentifier(callee) && id.type === 'Identifier') {
for (const ref of resolved.references) {
if (ref !== id) {
useEventVariables.add(ref.identifier);
}
}
// useEvent() return value is always unstable.
return true;
} else if (name === 'useState' || name === 'useReducer') {
// Only consider second value in initializing tuple stable.
if (
id.type === 'ArrayPattern' &&
id.elements.length === 2 &&
isArray(resolved.identifiers)
) {
// Is second tuple value the same reference we're checking?
if (id.elements[1] === resolved.identifiers[0]) {
if (name === 'useState') {
const references = resolved.references;
let writeCount = 0;
for (let i = 0; i < references.length; i++) {
if (references[i].isWrite()) {
writeCount++;
}
if (writeCount > 1) {
return false;
}
setStateCallSites.set(
references[i].identifier,
id.elements[0],
);
}
}
// Setter is stable.
return true;
} else if (id.elements[0] === resolved.identifiers[0]) {
if (name === 'useState') {
const references = resolved.references;
for (let i = 0; i < references.length; i++) {
stateVariables.add(references[i].identifier);
}
}
// State variable itself is dynamic.
return false;
}
}
} else if (name === 'useTransition') {
// Only consider second value in initializing tuple stable.
if (
id.type === 'ArrayPattern' &&
id.elements.length === 2 &&
Array.isArray(resolved.identifiers)
) {
// Is second tuple value the same reference we're checking?
if (id.elements[1] === resolved.identifiers[0]) {
// Setter is stable.
return true;
}
}
}
// By default assume it's dynamic.
return false;
}
// Some are just functions that don't reference anything dynamic.
function isFunctionWithoutCapturedValues(resolved) {
if (!isArray(resolved.defs)) {
return false;
}
const def = resolved.defs[0];
if (def == null) {
return false;
}
if (def.node == null || def.node.id == null) {
return false;
}
// Search the direct component subscopes for
// top-level function definitions matching this reference.
const fnNode = def.node;
const childScopes = componentScope.childScopes;
let fnScope = null;
let i;
for (i = 0; i < childScopes.length; i++) {
const childScope = childScopes[i];
const childScopeBlock = childScope.block;
if (
// function handleChange() {}
(fnNode.type === 'FunctionDeclaration' &&
childScopeBlock === fnNode) ||
// const handleChange = () => {}
// const handleChange = function() {}
(fnNode.type === 'VariableDeclarator' &&
childScopeBlock.parent === fnNode)
) {
// Found it!
fnScope = childScope;
break;
}
}
if (fnScope == null) {
return false;
}
// Does this function capture any values
// that are in pure scopes (aka render)?
for (i = 0; i < fnScope.through.length; i++) {
const ref = fnScope.through[i];
if (ref.resolved == null) {
continue;
}
if (
pureScopes.has(ref.resolved.scope) &&
// Stable values are fine though,
// although we won't check functions deeper.
!memoizedIsStableKnownHookValue(ref.resolved)
) {
return false;
}
}
// If we got here, this function doesn't capture anything
// from render--or everything it captures is known stable.
return true;
}
// Remember such values. Avoid re-running extra checks on them.
const memoizedIsStableKnownHookValue = memoizeWithWeakMap(
isStableKnownHookValue,
stableKnownValueCache,
);
const memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(
isFunctionWithoutCapturedValues,
functionWithoutCapturedValueCache,
);
// These are usually mistaken. Collect them.
const currentRefsInEffectCleanup = new Map();
// Is this reference inside a cleanup function for this effect node?
// We can check by traversing scopes upwards from the reference, and checking
// if the last "return () => " we encounter is located directly inside the effect.
function isInsideEffectCleanup(reference) {
let curScope = reference.from;
let isInReturnedFunction = false;
while (curScope.block !== node) {
if (curScope.type === 'function') {
isInReturnedFunction =
curScope.block.parent != null &&
curScope.block.parent.type === 'ReturnStatement';
}
curScope = curScope.upper;
}
return isInReturnedFunction;
}
// Get dependencies from all our resolved references in pure scopes.
// Key is dependency string, value is whether it's stable.
const dependencies = new Map();
const optionalChains = new Map();
gatherDependenciesRecursively(scope);
function gatherDependenciesRecursively(currentScope) {
for (const reference of currentScope.references) {
// If this reference is not resolved or it is not declared in a pure
// scope then we don't care about this reference.
if (!reference.resolved) {
continue;
}
if (!pureScopes.has(reference.resolved.scope)) {
continue;
}
// Narrow the scope of a dependency if it is, say, a member expression.
// Then normalize the narrowed dependency.
const referenceNode = fastFindReferenceWithParent(
node,
reference.identifier,
);
const dependencyNode = getDependency(referenceNode);
const dependency = analyzePropertyChain(
dependencyNode,
optionalChains,
);
// Accessing ref.current inside effect cleanup is bad.
if (
// We're in an effect...
isEffect &&
// ... and this look like accessing .current...
dependencyNode.type === 'Identifier' &&
(dependencyNode.parent.type === 'MemberExpression' ||
dependencyNode.parent.type === 'OptionalMemberExpression') &&
!dependencyNode.parent.computed &&
dependencyNode.parent.property.type === 'Identifier' &&
dependencyNode.parent.property.name === 'current' &&
// ...in a cleanup function or below...
isInsideEffectCleanup(reference)
) {
currentRefsInEffectCleanup.set(dependency, {
reference,
dependencyNode,
});
}
if (
dependencyNode.parent.type === 'TSTypeQuery' ||
dependencyNode.parent.type === 'TSTypeReference'
) {
continue;
}
const def = reference.resolved.defs[0];
if (def == null) {
continue;
}
// Ignore references to the function itself as it's not defined yet.
if (def.node != null && def.node.init === node.parent) {
continue;
}
// Ignore Flow type parameters
if (def.type === 'TypeParameter') {
continue;
}
// Add the dependency to a map so we can make sure it is referenced
// again in our dependencies array. Remember whether it's stable.
if (!dependencies.has(dependency)) {
const resolved = reference.resolved;
const isStable =
memoizedIsStableKnownHookValue(resolved) ||
memoizedIsFunctionWithoutCapturedValues(resolved);
dependencies.set(dependency, {
isStable,
references: [reference],
});
} else {
dependencies.get(dependency).references.push(reference);
}
}
for (const childScope of currentScope.childScopes) {
gatherDependenciesRecursively(childScope);
}
}
// Warn about accessing .current in cleanup effects.
currentRefsInEffectCleanup.forEach(
({reference, dependencyNode}, dependency) => {
const references = reference.resolved.references;
// Is React managing this ref or us?
// Let's see if we can find a .current assignment.
let foundCurrentAssignment = false;
for (let i = 0; i < references.length; i++) {
const {identifier} = references[i];
const {parent} = identifier;
if (
parent != null &&
// ref.current
// Note: no need to handle OptionalMemberExpression because it can't be LHS.
parent.type === 'MemberExpression' &&
!parent.computed &&
parent.property.type === 'Identifier' &&
parent.property.name === 'current' &&
// ref.current = <something>
parent.parent.type === 'AssignmentExpression' &&
parent.parent.left === parent
) {
foundCurrentAssignment = true;
break;
}
}
// We only want to warn about React-managed refs.
if (foundCurrentAssignment) {
return;
}
reportProblem({
node: dependencyNode.parent.property,
message:
`The ref value '${dependency}.current' will likely have ` +
`changed by the time this effect cleanup function runs. If ` +
`this ref points to a node rendered by React, copy ` +
`'${dependency}.current' to a variable inside the effect, and ` +
`use that variable in the cleanup function.`,
});
},
);
// Warn about assigning to variables in the outer scope.
// Those are usually bugs.
const staleAssignments = new Set();
function reportStaleAssignment(writeExpr, key) {
if (staleAssignments.has(key)) {
return;
}
staleAssignments.add(key);
reportProblem({
node: writeExpr,
message:
`Assignments to the '${key}' variable from inside React Hook ` +
`${context.getSource(reactiveHook)} will be lost after each ` +
`render. To preserve the value over time, store it in a useRef ` +
`Hook and keep the mutable value in the '.current' property. ` +
`Otherwise, you can move this variable directly inside ` +
`${context.getSource(reactiveHook)}.`,
});
}
// Remember which deps are stable and report bad usage first.
const stableDependencies = new Set();
dependencies.forEach(({isStable, references}, key) => {
if (isStable) {
stableDependencies.add(key);
}
references.forEach(reference => {
if (reference.writeExpr) {
reportStaleAssignment(reference.writeExpr, key);
}
});
});
if (staleAssignments.size > 0) {
// The intent isn't clear so we'll wait until you fix those first.
return;
}
if (!declaredDependenciesNode) {
// Check if there are any top-level setState() calls.
// Those tend to lead to infinite loops.
let setStateInsideEffectWithoutDeps = null;
dependencies.forEach(({isStable, references}, key) => {
if (setStateInsideEffectWithoutDeps) {
return;
}
references.forEach(reference => {
if (setStateInsideEffectWithoutDeps) {
return;
}
const id = reference.identifier;
const isSetState = setStateCallSites.has(id);
if (!isSetState) {
return;
}
let fnScope = reference.from;
while (fnScope.type !== 'function') {
fnScope = fnScope.upper;
}
const isDirectlyInsideEffect = fnScope.block === node;
if (isDirectlyInsideEffect) {
// TODO: we could potentially ignore early returns.
setStateInsideEffectWithoutDeps = key;
}
});
});
if (setStateInsideEffectWithoutDeps) {
const {suggestedDependencies} = collectRecommendations({
dependencies,
declaredDependencies: [],
stableDependencies,
externalDependencies: new Set(),
isEffect: true,
});
reportProblem({
node: reactiveHook,
message:
`React Hook ${reactiveHookName} contains a call to '${setStateInsideEffectWithoutDeps}'. ` +
`Without a list of dependencies, this can lead to an infinite chain of updates. ` +
`To fix this, pass [` +
suggestedDependencies.join(', ') +
`] as a second argument to the ${reactiveHookName} Hook.`,
suggest: [
{
desc: `Add dependencies array: [${suggestedDependencies.join(
', ',
)}]`,
fix(fixer) {
return fixer.insertTextAfter(
node,
`, [${suggestedDependencies.join(', ')}]`,
);
},
},
],
});
}
return;
}
const declaredDependencies = [];
const externalDependencies = new Set();
if (declaredDependenciesNode.type !== 'ArrayExpression') {
// If the declared dependencies are not an array expression then we
// can't verify that the user provided the correct dependencies. Tell
// the user this in an error.
reportProblem({
node: declaredDependenciesNode,
message:
`React Hook ${context.getSource(reactiveHook)} was passed a ` +
'dependency list that is not an array literal. This means we ' +
"can't statically verify whether you've passed the correct " +
'dependencies.',
});
} else {
declaredDependenciesNode.elements.forEach(declaredDependencyNode => {
// Skip elided elements.
if (declaredDependencyNode === null) {
return;
}
// If we see a spread element then add a special warning.
if (declaredDependencyNode.type === 'SpreadElement') {
reportProblem({
node: declaredDependencyNode,
message:
`React Hook ${context.getSource(reactiveHook)} has a spread ` +
"element in its dependency array. This means we can't " +
"statically verify whether you've passed the " +
'correct dependencies.',
});
return;
}
if (useEventVariables.has(declaredDependencyNode)) {
reportProblem({
node: declaredDependencyNode,
message:
'Functions returned from `useEvent` must not be included in the dependency array. ' +
`Remove \`${context.getSource(
declaredDependencyNode,
)}\` from the list.`,
suggest: [
{
desc: `Remove the dependency \`${context.getSource(
declaredDependencyNode,
)}\``,
fix(fixer) {
return fixer.removeRange(declaredDependencyNode.range);
},
},
],
});
}
// Try to normalize the declared dependency. If we can't then an error
// will be thrown. We will catch that error and report an error.
let declaredDependency;
try {
declaredDependency = analyzePropertyChain(
declaredDependencyNode,
null,
);
} catch (error) {
if (/Unsupported node type/.test(error.message)) {
if (declaredDependencyNode.type === 'Literal') {
if (dependencies.has(declaredDependencyNode.value)) {
reportProblem({
node: declaredDependencyNode,
message:
`The ${declaredDependencyNode.raw} literal is not a valid dependency ` +
`because it never changes. ` +
`Did you mean to include ${declaredDependencyNode.value} in the array instead?`,
});
} else {
reportProblem({
node: declaredDependencyNode,
message:
`The ${declaredDependencyNode.raw} literal is not a valid dependency ` +
'because it never changes. You can safely remove it.',
});
}
} else {
reportProblem({
node: declaredDependencyNode,
message:
`React Hook ${context.getSource(reactiveHook)} has a ` +
`complex expression in the dependency array. ` +
'Extract it to a separate variable so it can be statically checked.',
});
}
return;
} else {
throw error;
}
}
let maybeID = declaredDependencyNode;
while (
maybeID.type === 'MemberExpression' ||
maybeID.type === 'OptionalMemberExpression' ||
maybeID.type === 'ChainExpression'
) {
maybeID = maybeID.object || maybeID.expression.object;
}
const isDeclaredInComponent = !componentScope.through.some(
ref => ref.identifier === maybeID,
);
// Add the dependency to our declared dependency map.
declaredDependencies.push({
key: declaredDependency,
node: declaredDependencyNode,
});
if (!isDeclaredInComponent) {
externalDependencies.add(declaredDependency);
}
});
}
const {
suggestedDependencies,
unnecessaryDependencies,
missingDependencies,
duplicateDependencies,
} = collectRecommendations({
dependencies,
declaredDependencies,
stableDependencies,
externalDependencies,
isEffect,
});
let suggestedDeps = suggestedDependencies;
const problemCount =
duplicateDependencies.size +
missingDependencies.size +
unnecessaryDependencies.size;
if (problemCount === 0) {
// If nothing else to report, check if some dependencies would
// invalidate on every render.
const constructions = scanForConstructions({
declaredDependencies,
declaredDependenciesNode,
componentScope,
scope,
});
constructions.forEach(
({construction, isUsedOutsideOfHook, depType}) => {
const wrapperHook =
depType === 'function' ? 'useCallback' : 'useMemo';
const constructionType =
depType === 'function' ? 'definition' : 'initialization';
const defaultAdvice = `wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`;
const advice = isUsedOutsideOfHook
? `To fix this, ${defaultAdvice}`
: `Move it inside the ${reactiveHookName} callback. Alternatively, ${defaultAdvice}`;
const causation =
depType === 'conditional' || depType === 'logical expression'
? 'could make'
: 'makes';
const message =
`The '${construction.name.name}' ${depType} ${causation} the dependencies of ` +
`${reactiveHookName} Hook (at line ${declaredDependenciesNode.loc.start.line}) ` +
`change on every render. ${advice}`;
let suggest;
// Only handle the simple case of variable assignments.
// Wrapping function declarations can mess up hoisting.
if (
isUsedOutsideOfHook &&
construction.type === 'Variable' &&
// Objects may be mutated after construction, which would make this
// fix unsafe. Functions _probably_ won't be mutated, so we'll
// allow this fix for them.
depType === 'function'
) {
suggest = [
{
desc: `Wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`,
fix(fixer) {
const [before, after] =
wrapperHook === 'useMemo'
? [`useMemo(() => { return `, '; })']
: ['useCallback(', ')'];
return [
// TODO: also add an import?
fixer.insertTextBefore(construction.node.init, before),
// TODO: ideally we'd gather deps here but it would require
// restructuring the rule code. This will cause a new lint
// error to appear immediately for useCallback. Note we're
// not adding [] because would that changes semantics.
fixer.insertTextAfter(construction.node.init, after),
];
},
},
];
}
// TODO: What if the function needs to change on every render anyway?
// Should we suggest removing effect deps as an appropriate fix too?
reportProblem({
// TODO: Why not report this at the dependency site?
node: construction.node,
message,
suggest,
});
},
);
return;
}
// If we're going to report a missing dependency,
// we might as well recalculate the list ignoring
// the currently specified deps. This can result
// in some extra deduplication. We can't do this
// for effects though because those have legit
// use cases for over-specifying deps.
if (!isEffect && missingDependencies.size > 0) {
suggestedDeps = collectRecommendations({
dependencies,
declaredDependencies: [], // Pretend we don't know
stableDependencies,
externalDependencies,
isEffect,
}).suggestedDependencies;
}
// Alphabetize the suggestions, but only if deps were already alphabetized.
function areDeclaredDepsAlphabetized() {
if (declaredDependencies.length === 0) {
return true;
}
const declaredDepKeys = declaredDependencies.map(dep => dep.key);
const sortedDeclaredDepKeys = declaredDepKeys.slice().sort();
return declaredDepKeys.join(',') === sortedDeclaredDepKeys.join(',');
}
if (areDeclaredDepsAlphabetized()) {
suggestedDeps.sort();
}
// Most of our algorithm deals with dependency paths with optional chaining stripped.
// This function is the last step before printing a dependency, so now is a good time to
// check whether any members in our path are always used as optional-only. In that case,
// we will use ?. instead of . to concatenate those parts of the path.
function formatDependency(path) {
const members = path.split('.');
let finalPath = '';
for (let i = 0; i < members.length; i++) {
if (i !== 0) {
const pathSoFar = members.slice(0, i + 1).join('.');
const isOptional = optionalChains.get(pathSoFar) === true;
finalPath += isOptional ? '?.' : '.';
}
finalPath += members[i];
}
return finalPath;
}
function getWarningMessage(deps, singlePrefix, label, fixVerb) {
if (deps.size === 0) {
return null;
}
return (
(deps.size > 1 ? '' : singlePrefix + ' ') +
label +
' ' +
(deps.size > 1 ? 'dependencies' : 'dependency') +
': ' +
joinEnglish(
Array.from(deps)
.sort()
.map(name => "'" + formatDependency(name) + "'"),
) +
`. Either ${fixVerb} ${
deps.size > 1 ? 'them' : 'it'
} or remove the dependency array.`
);
}
let extraWarning = '';
if (unnecessaryDependencies.size > 0) {
let badRef = null;
Array.from(unnecessaryDependencies.keys()).forEach(key => {
if (badRef !== null) {
return;
}
if (key.endsWith('.current')) {
badRef = key;
}
});
if (badRef !== null) {
extraWarning =
` Mutable values like '${badRef}' aren't valid dependencies ` +
"because mutating them doesn't re-render the component.";
} else if (externalDependencies.size > 0) {
const dep = Array.from(externalDependencies)[0];
// Don't show this warning for things that likely just got moved *inside* the callback
// because in that case they're clearly not referring to globals.
if (!scope.set.has(dep)) {
extraWarning =
` Outer scope values like '${dep}' aren't valid dependencies ` +
`because mutating them doesn't re-render the component.`;
}
}
}
// `props.foo()` marks `props` as a dependency because it has
// a `this` value. This warning can be confusing.
// So if we're going to show it, append a clarification.
if (!extraWarning && missingDependencies.has('props')) {
const propDep = dependencies.get('props');
if (propDep == null) {
return;
}
const refs = propDep.references;
if (!Array.isArray(refs)) {
return;
}
let isPropsOnlyUsedInMembers = true;
for (let i = 0; i < refs.length; i++) {
const ref = refs[i];
const id = fastFindReferenceWithParent(
componentScope.block,
ref.identifier,
);
if (!id) {
isPropsOnlyUsedInMembers = false;
break;
}
const parent = id.parent;
if (parent == null) {
isPropsOnlyUsedInMembers = false;
break;
}
if (
parent.type !== 'MemberExpression' &&
parent.type !== 'OptionalMemberExpression'
) {
isPropsOnlyUsedInMembers = false;
break;
}
}
if (isPropsOnlyUsedInMembers) {
extraWarning =
` However, 'props' will change when *any* prop changes, so the ` +
`preferred fix is to destructure the 'props' object outside of ` +
`the ${reactiveHookName} call and refer to those specific props ` +
`inside ${context.getSource(reactiveHook)}.`;
}
}
if (!extraWarning && missingDependencies.size > 0) {
// See if the user is trying to avoid specifying a callable prop.
// This usually means they're unaware of useCallback.
let missingCallbackDep = null;
missingDependencies.forEach(missingDep => {
if (missingCallbackDep) {
return;
}
// Is this a variable from top scope?
const topScopeRef = componentScope.set.get(missingDep);
const usedDep = dependencies.get(missingDep);
if (usedDep.references[0].resolved !== topScopeRef) {
return;
}
// Is this a destructured prop?
const def = topScopeRef.defs[0];
if (def == null || def.name == null || def.type !== 'Parameter') {
return;
}
// Was it called in at least one case? Then it's a function.
let isFunctionCall = false;
let id;
for (let i = 0; i < usedDep.references.length; i++) {
id = usedDep.references[i].identifier;
if (
id != null &&
id.parent != null &&
(id.parent.type === 'CallExpression' ||