Skip to content

Commit f1ff434

Browse files
authored
Don't suggest a function as its own dep (#15115)
1 parent 371bbf3 commit f1ff434

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

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

+66
Original file line numberDiff line numberDiff line change
@@ -972,6 +972,26 @@ const tests = {
972972
}
973973
`,
974974
},
975+
{
976+
code: `
977+
function Example() {
978+
const foo = useCallback(() => {
979+
foo();
980+
}, []);
981+
}
982+
`,
983+
},
984+
{
985+
code: `
986+
function Example({ prop }) {
987+
const foo = useCallback(() => {
988+
if (prop) {
989+
foo();
990+
}
991+
}, [prop]);
992+
}
993+
`,
994+
},
975995
],
976996
invalid: [
977997
{
@@ -4441,6 +4461,52 @@ const tests = {
44414461
`This lets you handle multiple requests without bugs.`,
44424462
],
44434463
},
4464+
{
4465+
code: `
4466+
function Example() {
4467+
const foo = useCallback(() => {
4468+
foo();
4469+
}, [foo]);
4470+
}
4471+
`,
4472+
output: `
4473+
function Example() {
4474+
const foo = useCallback(() => {
4475+
foo();
4476+
}, []);
4477+
}
4478+
`,
4479+
errors: [
4480+
"React Hook useCallback has an unnecessary dependency: 'foo'. " +
4481+
'Either exclude it or remove the dependency array.',
4482+
],
4483+
},
4484+
{
4485+
code: `
4486+
function Example({ prop }) {
4487+
const foo = useCallback(() => {
4488+
prop.hello(foo);
4489+
}, [foo]);
4490+
const bar = useCallback(() => {
4491+
foo();
4492+
}, [foo]);
4493+
}
4494+
`,
4495+
output: `
4496+
function Example({ prop }) {
4497+
const foo = useCallback(() => {
4498+
prop.hello(foo);
4499+
}, [prop]);
4500+
const bar = useCallback(() => {
4501+
foo();
4502+
}, [foo]);
4503+
}
4504+
`,
4505+
errors: [
4506+
"React Hook useCallback has a missing dependency: 'prop'. " +
4507+
'Either include it or remove the dependency array.',
4508+
],
4509+
},
44444510
],
44454511
};
44464512

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

+10
Original file line numberDiff line numberDiff line change
@@ -401,6 +401,16 @@ export default {
401401
});
402402
}
403403

404+
// Ignore references to the function itself as it's not defined yet.
405+
const def = reference.resolved.defs[0];
406+
if (
407+
def != null &&
408+
def.node != null &&
409+
def.node.init === node.parent
410+
) {
411+
continue;
412+
}
413+
404414
// Add the dependency to a map so we can make sure it is referenced
405415
// again in our dependencies array. Remember whether it's static.
406416
if (!dependencies.has(dependency)) {

0 commit comments

Comments
 (0)