react_auditor/rules/react/
no_set_state_in_effect.rs1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7pub struct NoSetStateInEffect;
8
9const RULE_META: RuleMeta = RuleMeta {
10 id: "no-set-state-in-effect",
11 default_severity: Severity::Warning,
12 category: "react",
13 description: "Avoid calling setState in useEffect without conditions",
14};
15
16impl Rule for NoSetStateInEffect {
17 fn meta(&self) -> &RuleMeta {
18 &RULE_META
19 }
20
21 fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
22 let mut collector = SetStateEffectCollector {
23 findings: Vec::new(),
24 source: source_text,
25 in_effect: false,
26 };
27 collector.visit_program(program);
28 collector.findings
29 }
30}
31
32struct SetStateEffectCollector<'a> {
33 findings: Vec<RuleFinding>,
34 source: &'a str,
35 in_effect: bool,
36}
37
38impl<'a> SetStateEffectCollector<'a> {
39 fn add_finding(&mut self, start: usize, msg: String) {
40 let line = self.source[..start].lines().count().max(1);
41 let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
42 self.findings.push(RuleFinding {
43 line,
44 column: col + 1,
45 message: msg,
46 });
47 }
48}
49
50impl<'a> Visit<'a> for SetStateEffectCollector<'a> {
51 fn visit_call_expression(&mut self, expr: &oxc_ast::ast::CallExpression<'a>) {
52 let name = if let oxc_ast::ast::Expression::Identifier(ident) = &expr.callee {
53 ident.name.as_str()
54 } else {
55 return;
56 };
57
58 if name == "useEffect" || name == "useLayoutEffect" {
59 self.in_effect = true;
60 oxc_ast_visit::walk::walk_call_expression(self, expr);
61 self.in_effect = false;
62 return;
63 }
64
65 if self.in_effect
66 && (name.starts_with("set")
67 && name.len() > 3
68 && name.as_bytes()[3].is_ascii_uppercase())
69 {
70 self.add_finding(expr.span.start as usize,
71 format!("`{name}` called inside useEffect without dependencies — may cause infinite loop"));
72 }
73
74 if self.in_effect && name == "dispatch" {
75 self.add_finding(
76 expr.span.start as usize,
77 "Store dispatch in useEffect without dependencies — may cause infinite loop"
78 .to_string(),
79 );
80 }
81 }
82}