Skip to content

Commit 29d560b

Browse files
committed
[POC] Warn on constant constructions coming from default params
This seems to work, but we would probably want to improve the error message for this case.
1 parent 1d5e10f commit 29d560b

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7518,6 +7518,42 @@ const tests = {
75187518
},
75197519
],
75207520
},
7521+
{
7522+
only: true,
7523+
code: normalizeIndent`
7524+
function Foo({foo = []}) {
7525+
useEffect(() => {
7526+
console.log(foo);
7527+
}, [foo]);
7528+
}
7529+
`,
7530+
errors: [
7531+
{
7532+
message:
7533+
"The 'foo' array makes the dependencies of useEffect Hook (at line 5) change on every render. " +
7534+
"Move it inside the useEffect callback. Alternatively, wrap the initialization of 'foo' in its own useMemo() Hook.",
7535+
suggestions: undefined,
7536+
},
7537+
],
7538+
},
7539+
{
7540+
only: true,
7541+
code: normalizeIndent`
7542+
function useFoo(foo = []) {
7543+
useEffect(() => {
7544+
console.log(foo);
7545+
}, [foo]);
7546+
}
7547+
`,
7548+
errors: [
7549+
{
7550+
message:
7551+
"The 'foo' array makes the dependencies of useEffect Hook (at line 5) change on every render. " +
7552+
"Move it inside the useEffect callback. Alternatively, wrap the initialization of 'foo' in its own useMemo() Hook.",
7553+
suggestions: undefined,
7554+
},
7555+
],
7556+
},
75217557
],
75227558
};
75237559

packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1474,11 +1474,27 @@ function scanForConstructions({
14741474
if (node == null) {
14751475
return null;
14761476
}
1477+
1478+
// function(foo = []) {}
1479+
// function({foo = []}) {}
1480+
if (
1481+
node.type === 'Parameter' &&
1482+
node.name.parent.type === 'AssignmentPattern'
1483+
) {
1484+
const constantExpressionType = getConstructionExpressionType(
1485+
node.name.parent.right,
1486+
);
1487+
if (constantExpressionType != null) {
1488+
return [ref, constantExpressionType];
1489+
}
1490+
}
1491+
14771492
// const handleChange = function () {}
14781493
// const handleChange = () => {}
14791494
// const foo = {}
14801495
// const foo = []
14811496
// etc.
1497+
14821498
if (
14831499
node.type === 'Variable' &&
14841500
node.node.type === 'VariableDeclarator' &&

0 commit comments

Comments
 (0)