-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathrules_of_hooks.rs
More file actions
1684 lines (1622 loc) · 57.1 KB
/
Copy pathrules_of_hooks.rs
File metadata and controls
1684 lines (1622 loc) · 57.1 KB
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
use std::borrow::Cow;
use oxc_ast::{
AstKind,
ast::{ArrowFunctionExpression, Function},
};
use oxc_cfg::{
ControlFlowGraph, EdgeType, ErrorEdgeKind, InstructionKind,
graph::{algo, visit::Control},
};
use oxc_macros::declare_oxc_lint;
use oxc_semantic::{AstNodes, NodeId};
use oxc_syntax::operator::AssignmentOperator;
use crate::{
AstNode,
context::LintContext,
rule::Rule,
utils::{is_react_component_or_hook_name, is_react_function_call, is_react_hook},
};
mod diagnostics {
use oxc_diagnostics::OxcDiagnostic;
use oxc_span::Span;
const SCOPE: &str = "eslint-plugin-react-hooks";
pub(super) fn function_error(span: Span, hook_name: &str, func_name: &str) -> OxcDiagnostic {
OxcDiagnostic::warn(format!(
"React Hook {hook_name:?} is called in function {func_name:?} that is neither \
a React function component nor a custom React Hook function. \
React component names must start with an uppercase letter. \
React Hook names must start with the word \"use\".",
))
.with_label(span)
.with_error_code_scope(SCOPE)
}
pub(super) fn conditional_hook(span: Span, hook_name: &str) -> OxcDiagnostic {
OxcDiagnostic::warn(format!(
"React Hook {hook_name:?} is called conditionally. React Hooks must be \
called in the exact same order in every component render."
))
.with_label(span)
.with_error_code_scope(SCOPE)
}
pub(super) fn loop_hook(span: Span, hook_name: &str) -> OxcDiagnostic {
OxcDiagnostic::warn(format!(
"React Hook {hook_name:?} may be executed more than once. Possibly \
because it is called in a loop. React Hooks must be called in the \
exact same order in every component render."
))
.with_label(span)
.with_error_code_scope(SCOPE)
}
pub(super) fn top_level_hook(span: Span, hook_name: &str) -> OxcDiagnostic {
OxcDiagnostic::warn(format!(
"React Hook {hook_name:?} cannot be called at the top level. React Hooks \
must be called in a React function component or a custom React \
Hook function."
))
.with_label(span)
.with_error_code_scope(SCOPE)
}
pub(super) fn async_component(span: Span, func_name: &str) -> OxcDiagnostic {
OxcDiagnostic::warn(format!(
"message: `React Hook {func_name:?} cannot be called in an async function. "
))
.with_label(span)
.with_error_code_scope(SCOPE)
}
pub(super) fn class_component(span: Span, hook_name: &str) -> OxcDiagnostic {
OxcDiagnostic::warn(format!(
"React Hook {hook_name:?} cannot be called in a class component. React Hooks \
must be called in a React function component or a custom React \
Hook function."
))
.with_label(span)
.with_error_code_scope(SCOPE)
}
pub(super) fn generic_error(span: Span, hook_name: &str) -> OxcDiagnostic {
OxcDiagnostic::warn(format!(
"React Hook {hook_name:?} cannot be called inside a callback. React Hooks \
must be called in a React function component or a custom React \
Hook function."
))
.with_label(span)
.with_error_code_scope(SCOPE)
}
}
#[derive(Debug, Default, Clone)]
pub struct RulesOfHooks;
declare_oxc_lint!(
/// ### What it does
///
/// This enforces the Rules of Hooks
///
/// <https://reactjs.org/docs/hooks-rules.html>
///
RulesOfHooks,
react,
pedantic
);
impl Rule for RulesOfHooks {
fn should_run(&self, ctx: &crate::rules::ContextHost) -> bool {
// disable this rule in vue/nuxt and svelte(kit) files
// react hook can be build in only `.ts` files,
// but `useX` functions are popular and can be false positive in other frameworks
!ctx.file_path().extension().is_some_and(|ext| ext == "vue" || ext == "svelte")
}
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
let AstKind::CallExpression(call) = node.kind() else { return };
if !is_react_hook(&call.callee) {
return;
}
let cfg = ctx.cfg();
let span = call.span;
let hook_name =
call.callee_name().expect("We identify hooks using their names so it should be named.");
let nodes = ctx.nodes();
let is_use = is_react_function_call(call, "use");
let Some(parent_func) = parent_func(nodes, node) else {
return ctx.diagnostic(diagnostics::top_level_hook(span, hook_name));
};
// Check if our parent function is part of a class.
if matches!(
nodes.parent_kind(parent_func.id()),
Some(
AstKind::MethodDefinition(_)
| AstKind::StaticBlock(_)
| AstKind::PropertyDefinition(_)
)
) {
return ctx.diagnostic(diagnostics::class_component(span, hook_name));
}
match parent_func.kind() {
// We are in a named function that isn't a hook or component, which is illegal
AstKind::Function(Function { id: Some(id), .. })
if !is_react_component_or_hook_name(&id.name) =>
{
return ctx.diagnostic(diagnostics::function_error(
id.span,
hook_name,
id.name.as_str(),
));
}
// Hooks are allowed inside of unnamed functions used as arguments. As long as they are
// not used as a callback inside of components or hooks.
AstKind::Function(Function { id: None, .. }) | AstKind::ArrowFunctionExpression(_)
if is_non_react_func_arg(nodes, parent_func.id()) =>
{
// This rule doesn't apply to `use(...)`.
if !is_use && is_somewhere_inside_component_or_hook(nodes, parent_func.id()) {
ctx.diagnostic(diagnostics::generic_error(span, hook_name));
}
return;
}
AstKind::Function(Function { span, id: None, .. })
| AstKind::ArrowFunctionExpression(ArrowFunctionExpression {
span,
r#async: false,
..
}) => {
let ident = get_declaration_identifier(nodes, parent_func.id());
// Hooks cannot be used in a function declaration outside of a react component or hook.
// For example these are invalid:
// const notAComponent = () => {
// return () => {
// useState();
// }
// }
// --------------
// export default () => {
// if (isVal) {
// useState(0);
// }
// }
// --------------
// export default function() {
// if (isVal) {
// useState(0);
// }
// }
if ident.is_some_and(|name| !is_react_component_or_hook_name(&name)) {
return ctx.diagnostic(diagnostics::function_error(
*span,
hook_name,
"Anonymous",
));
}
}
// Hooks can't be called from async function.
AstKind::Function(Function { id: Some(id), r#async: true, .. }) => {
return ctx.diagnostic(diagnostics::async_component(id.span, id.name.as_str()));
}
// Hooks can't be called from async arrow function.
AstKind::ArrowFunctionExpression(ArrowFunctionExpression {
span,
r#async: true,
..
}) => {
return ctx.diagnostic(diagnostics::async_component(*span, "Anonymous"));
}
_ => {}
}
// `use(...)` can be called conditionally, And,
// `use(...)` can be called within a loop.
// So we don't need the following checks.
if is_use {
return;
}
let node_cfg_id = node.cfg_id();
let func_cfg_id = parent_func.cfg_id();
// there is no branch between us and our parent function
if node_cfg_id == func_cfg_id {
return;
}
if !cfg.is_reachable(func_cfg_id, node_cfg_id) {
// There should always be a control flow path between a parent and child node.
// If there is none it means we always do an early exit before reaching our hook call.
// In some cases it might mean that we are operating on an invalid `cfg` but in either
// case, It is somebody else's problem so we just return.
return;
}
// Is this node cyclic?
if cfg.is_cyclic(node_cfg_id) {
return ctx.diagnostic(diagnostics::loop_hook(span, hook_name));
}
if has_conditional_path_accept_throw(cfg, parent_func, node) {
#[expect(clippy::needless_return)]
return ctx.diagnostic(diagnostics::conditional_hook(span, hook_name));
}
}
}
fn has_conditional_path_accept_throw(
cfg: &ControlFlowGraph,
from: &AstNode<'_>,
to: &AstNode<'_>,
) -> bool {
let from_graph_id = from.cfg_id();
let to_graph_id = to.cfg_id();
let graph = cfg.graph();
if graph
.edges(to_graph_id)
.any(|it| matches!(it.weight(), EdgeType::Error(ErrorEdgeKind::Explicit)))
{
// TODO: We are simplifying here, There is a real need for a trait like `MayThrow` that
// would provide a method `may_throw`, since not everything may throw and break the control flow.
return true;
// let paths = algo::all_simple_paths::<Vec<_>, _>(graph, from_graph_id, to_graph_id, 0, None);
// if paths
// .flatten()
// .flat_map(|id| cfg.basic_block(id).instructions())
// .filter_map(|it| match it {
// Instruction { kind: InstructionKind::Statement, node_id: Some(node_id) } => {
// let r = Some(nodes.get_node(*node_id));
// dbg!(&r);
// r
// }
// _ => None,
// })
// .filter(|it| it.id() != to.id())
// .any(|it| {
// // TODO: it.may_throw()
// matches!(
// it.kind(),
// AstKind::ExpressionStatement(ExpressionStatement {
// expression: Expression::CallExpression(_),
// ..
// })
// )
// })
// {
// // return true;
// }
}
// All nodes should be able to reach the hook node, Otherwise we have a conditional/branching flow.
algo::dijkstra(graph, from_graph_id, Some(to_graph_id), |e| match e.weight() {
EdgeType::NewFunction | EdgeType::Error(ErrorEdgeKind::Implicit) => 1,
EdgeType::Error(ErrorEdgeKind::Explicit)
| EdgeType::Join
| EdgeType::Finalize
| EdgeType::Jump
| EdgeType::Unreachable
| EdgeType::Backedge
| EdgeType::Normal => 0,
})
.into_iter()
.filter(|(_, val)| *val == 0)
.any(|(f, _)| {
!cfg.is_reachable_filtered(f, to_graph_id, |it| {
if cfg
.basic_block(it)
.instructions()
.iter()
.any(|i| matches!(i.kind, InstructionKind::Throw))
{
Control::Break(true)
} else {
Control::Continue
}
})
})
}
fn parent_func<'a>(nodes: &'a AstNodes<'a>, node: &AstNode) -> Option<&'a AstNode<'a>> {
nodes
.ancestor_ids(node.id())
.map(|id| nodes.get_node(id))
.find(|it| it.kind().is_function_like())
}
/// Checks if the `node_id` is a callback argument,
/// And that function isn't a `React.memo` or `React.forwardRef`.
/// Returns `true` if this node is a function argument and that isn't a React special function.
/// Otherwise it would return `false`.
fn is_non_react_func_arg(nodes: &AstNodes, node_id: NodeId) -> bool {
let argument = match nodes.parent_node(node_id) {
Some(parent) if matches!(parent.kind(), AstKind::Argument(_)) => parent,
_ => return false,
};
let Some(AstKind::CallExpression(call)) = nodes.parent_kind(argument.id()) else {
return false;
};
!(is_react_function_call(call, "forwardRef") || is_react_function_call(call, "memo"))
}
fn is_somewhere_inside_component_or_hook(nodes: &AstNodes, node_id: NodeId) -> bool {
nodes
.ancestor_ids(node_id)
.map(|id| nodes.get_node(id))
.filter(|node| node.kind().is_function_like())
.map(|node| {
(
node.id(),
match node.kind() {
AstKind::Function(func) => func.name().map(Cow::from),
AstKind::ArrowFunctionExpression(_) => {
get_declaration_identifier(nodes, node.id())
}
_ => unreachable!(),
},
)
})
.any(|(id, ident)| {
ident.is_some_and(|name| is_react_component_or_hook_name(&name))
|| is_memo_or_forward_ref_callback(nodes, id)
})
}
fn get_declaration_identifier<'a>(
nodes: &'a AstNodes<'a>,
node_id: NodeId,
) -> Option<Cow<'a, str>> {
let node = nodes.get_node(node_id);
match node.kind() {
AstKind::Function(Function { id: Some(id), .. }) => {
// function useHook() {}
// const whatever = function useHook() {};
//
// Function declaration or function expression names win over any
// assignment statements or other renames.
Some(Cow::Borrowed(id.name.as_str()))
}
AstKind::Function(_) | AstKind::ArrowFunctionExpression(_) => {
let parent =
nodes.ancestor_ids(node_id).skip(1).map(|node| nodes.get_node(node)).next()?;
match parent.kind() {
AstKind::VariableDeclarator(decl) => {
decl.id.get_identifier_name().map(|id| Cow::Borrowed(id.as_str()))
}
// useHook = () => {};
AstKind::AssignmentExpression(expr)
if matches!(expr.operator, AssignmentOperator::Assign) =>
{
expr.left.get_identifier_name().map(std::convert::Into::into)
}
// const {useHook = () => {}} = {};
// ({useHook = () => {}} = {});
AstKind::AssignmentPattern(patt) => {
patt.left.get_identifier_name().map(|id| Cow::Borrowed(id.as_str()))
}
// { useHook: () => {} }
// { useHook() {} }
AstKind::ObjectProperty(prop) => prop.key.name(),
_ => None,
}
}
_ => None,
}
}
/// # Panics
/// `node_id` should always point to a valid `Function`.
fn is_memo_or_forward_ref_callback(nodes: &AstNodes, node_id: NodeId) -> bool {
nodes.ancestor_ids(node_id).map(|id| nodes.get_node(id)).any(|node| {
if let AstKind::CallExpression(call) = node.kind() {
call.callee_name().is_some_and(|name| matches!(name, "forwardRef" | "memo"))
} else {
false
}
})
}
#[test]
fn test() {
/// Copyright (c) Meta Platforms, Inc. and affiliates.
/// Most of these tests are sourced from the original react `eslint-plugin-react-hooks` package.
/// https://github.com/facebook/react/blob/5b903cdaa94c78e8fabb985d8daca5bd7d266323/packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.js
use crate::tester::Tester;
let pass = vec![
// Valid because components can use hooks.
"
function ComponentWithHook() {
useHook();
}
",
// Valid because hooks can be used in condition expressions beginning with a ternary condition
"
function ComponentWithConditionalHook() {
if (useHook() ? good() : bad()) {
check();
}
}
",
// Valid because hooks can be used in condition expressions
"
function Component() {
if (!useHasPermission()) {
return null;
}
return <Content />;
}
",
// Valid because hooks can be used in ternary condition expressions
"
function Component() {
return useHasPermission() ? <Content /> : null;
}
",
// Valid because hooks can be used in logical expressions (left side)
"
function Component() {
return useHasPermission() && <Content />;
}
",
// Valid because hooks can be used with negation in condition expressions
"
function Component() {
if (!useHasPermission()) {
return null;
}
return <Content />;
}
",
// Valid because hooks can be used in complex condition expressions
"
function Component() {
if (useHasPermission() && isAdmin()) {
return <AdminContent />;
}
return <Content />;
}
",
// Valid because hooks can be used in nested condition expressions
"
function Component() {
return (useHasPermission() && isAdmin()) ? <AdminContent /> : <Content />;
}
",
// Valid because components can use hooks.
"
function createComponentWithHook() {
return function ComponentWithHook() {
useHook();
};
}
",
// Valid because hooks can use hooks.
"
function useHookWithHook() {
useHook();
}
",
// Valid because hooks can use hooks.
"
function createHook() {
return function useHookWithHook() {
useHook();
}
}
",
// Valid because components can call functions.
"
function ComponentWithNormalFunction() {
doSomething();
}
",
// Valid because functions can call functions.
"
function normalFunctionWithNormalFunction() {
doSomething();
}
",
// Valid because functions can call functions.
"
function normalFunctionWithConditionalFunction() {
if (cond) {
doSomething();
}
}
",
// Valid because functions can call functions.
"
function functionThatStartsWithUseButIsntAHook() {
if (cond) {
userFetch();
}
}
",
// Valid although unconditional return doesn't make sense and would fail other rules.
// We could make it invalid but it doesn't matter.
"
function useUnreachable() {
return;
useHook();
}
",
// Valid because hooks can call hooks.
"
function useHook() { useState(); }
const whatever = function useHook() { useState(); };
const useHook1 = () => { useState(); };
let useHook2 = () => useState();
useHook2 = () => { useState(); };
({useHook: () => { useState(); }});
({useHook() { useState(); }});
const {useHook3 = () => { useState(); }} = {};
({useHook = () => { useState(); }} = {});
Namespace.useHook = () => { useState(); };
",
// Valid because hooks can call hooks.
"
function useHook() {
useHook1();
useHook2();
}
",
// Valid because hooks can call hooks.
"
function createHook() {
return function useHook() {
useHook1();
useHook2();
};
}
",
// Valid because hooks can call hooks.
"
function useHook() {
useState() && a;
}
",
// Valid because hooks can call hooks.
"
function useHook() {
return useHook1() + useHook2();
}
",
// Valid because hooks can call hooks.
"
function useHook() {
return useHook1(useHook2());
}
",
// Valid because hooks can be used in anonymous arrow-function arguments
// to forwardRef.
"
const FancyButton = React.forwardRef((props, ref) => {
useHook();
return <button {...props} ref={ref} />
});
",
// Valid because hooks can be used in anonymous function arguments to
// forwardRef.
"
const FancyButton = React.forwardRef(function (props, ref) {
useHook();
return <button {...props} ref={ref} />
});
",
// Valid because hooks can be used in anonymous function arguments to
// forwardRef.
"
const FancyButton = forwardRef(function (props, ref) {
useHook();
return <button {...props} ref={ref} />
});
",
// Valid because hooks can be used in anonymous function arguments to
// React.memo.
"
const MemoizedFunction = React.memo(props => {
useHook();
return <button {...props} />
});
",
// Valid because hooks can be used in anonymous function arguments to
// memo.
"
const MemoizedFunction = memo(function (props) {
useHook();
return <button {...props} />
});
",
// Valid because classes can call functions.
// We don't consider these to be hooks.
"
class C {
m() {
this.useHook();
super.useHook();
}
}
",
// Valid -- this is a regression test.
"
jest.useFakeTimers();
beforeEach(() => {
jest.useRealTimers();
})
",
// Valid because they're not matching use[A-Z].
"
fooState();
_use();
_useState();
use_hook();
// also valid because it's not matching the PascalCase namespace
jest.useFakeTimer()
",
// Regression test for some internal code.
// This shows how the "callback rule" is more relaxed,
// and doesn't kick in unless we're confident we're in
// a component or a hook.
"
function makeListener(instance) {
each(pixelsWithInferredEvents, pixel => {
if (useExtendedSelector(pixel.id) && extendedButton) {
foo();
}
});
}
",
// This is valid because "use"-prefixed functions called in
// unnamed function arguments are not assumed to be hooks.
"
React.unknownFunction((foo, bar) => {
if (foo) {
useNotAHook(bar)
}
});
",
// This is valid because "use"-prefixed functions called in
// unnamed function arguments are not assumed to be hooks.
"
unknownFunction(function(foo, bar) {
if (foo) {
useNotAHook(bar)
}
});
",
// Regression test for incorrectly flagged valid code.
"
function RegressionTest() {
const foo = cond ? a : b;
useState();
}
",
// Valid because exceptions abort rendering
"
function RegressionTest() {
if (page == null) {
throw new Error('oh no!');
}
useState();
}
",
// Valid because the loop doesn't change the order of hooks calls.
"
function RegressionTest(test) {
while (test) {
test = update(test);
}
React.useLayoutEffect(() => {});
}
",
// Valid because the loop doesn't change the order of hooks calls.
"
function RegressionTest() {
const res = [];
const additionalCond = true;
for (let i = 0; i !== 10 && additionalCond; ++i ) {
res.push(i);
}
React.useLayoutEffect(() => {});
}
",
// Is valid but hard to compute by brute-forcing
"
function MyComponent() {
// 40 conditions
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
if (c) {} else {}
// 10 hooks
useHook();
useHook();
useHook();
useHook();
useHook();
useHook();
useHook();
useHook();
useHook();
useHook();
}
",
// Valid because the neither the conditions before or after the hook affect the hook call
// Failed prior to implementing BigInt because pathsFromStartToEnd and allPathsFromStartToEnd were too big and had rounding errors
"
const useSomeHook = () => {};
const SomeName = () => {
const filler = FILLER ?? FILLER ?? FILLER;
const filler2 = FILLER ?? FILLER ?? FILLER;
const filler3 = FILLER ?? FILLER ?? FILLER;
const filler4 = FILLER ?? FILLER ?? FILLER;
const filler5 = FILLER ?? FILLER ?? FILLER;
const filler6 = FILLER ?? FILLER ?? FILLER;
const filler7 = FILLER ?? FILLER ?? FILLER;
const filler8 = FILLER ?? FILLER ?? FILLER;
useSomeHook();
if (anyConditionCanEvenBeFalse) {
return null;
}
return (
<React.Fragment>
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
{FILLER ? FILLER : FILLER}
</React.Fragment>
);
};
",
// Valid because the neither the condition nor the loop affect the hook call.
"
function App(props) {
const someObject = {propA: true};
for (const propName in someObject) {
if (propName === true) {
} else {
}
}
const [myState, setMyState] = useState(null);
}
",
"
function App() {
const text = use(Promise.resolve('A'));
return <Text text={text} />
}
",
"
import * as React from 'react';
function App() {
if (shouldShowText) {
const text = use(query);
const data = React.use(thing);
const data2 = react.use(thing2);
return <Text text={text} />
}
return <Text text={shouldFetchBackupText ? use(backupQuery) : \"Nothing to see here\"} />
}
",
"
function App() {
let data = [];
for (const query of queries) {
const text = use(item);
data.push(text);
}
return <Child data={data} />
}
",
"
function App() {
const data = someCallback((x) => use(x));
return <Child data={data} />
}
",
"
function useLabeledBlock() {
label: {
useHook();
if (a) break label;
}
}
",
"
export const FalsePositive = ({ editor, anchorElem, isLink, linkNodeUrl, close }: Props) => {
// This custom hook invocation seems to trigger false positives below
const [state, setState] = useCustomHook<State>({
inputLinkUrl: linkNodeUrl ?? '',
editable: !isLink,
lastLinkUrl: '',
lastSelection: null
});
const [someThing, setSomeThing] = useState(true);
const onEdit = useCallback(() => setSomeThing(false), [inputLinkUrl, setSomeThing]);
const updateLinkEditor = useCallback(() => {
const rootElement = editor.getRootElement();
if (nativeSelection.anchorNode === rootElement) {
let inner = rootElement;
while (inner.firstElementChild !== null) {
inner = inner.firstElementChild as HTMLElement;
}
}
}, [anchorElem, editor, setSomeThing]);
return <div>test</div>;
};
",
"
function useLabeledBlock() {
let x = () => {
if (some) {
noop();
}
};
useHook();
}
",
"
export const Component = () => {
return {
Target: () => {
useEffect(() => {
return () => {
something.value = true;
};
}, []);
return <div></div>;
},
useTargetModule: (m) => {
useModule(m);
},
};
};
",
"
test.beforeEach(async () => {
timer = Sinon.useFakeTimers({
toFake: ['setInterval'],
});
});
",
"export default function App() {
const [state, setState] = useState(0);
useEffect(() => {
console.log('Effect called');
}, []);
return <div>{state}</div>;
}
// https://github.com/toeverything/AFFiNE/blob/0ec1995addbb09fb5d4af765d84cc914b2905150/packages/frontend/core/src/hooks/use-query.ts#L46
",
"const createUseQuery =
(immutable: boolean): useQueryFn =>
(options, config) => {
const configWithSuspense: SWRConfiguration = useMemo(
() => ({