Don't suggest a function as its own dep (#15115)
Dan Abramov committed
Mar 15, 2019 at 15:14 UTC
f1ff4348c1debea8e0ce0fb35cc3fff342569789
2 files changed
+76
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
+66
@@ -972,6 +972,26 @@ const tests = {
972
}
973
`,
974
},
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
+ },
995
],
996
invalid: [
997
{
@@ -4441,6 +4461,52 @@ const tests = {
4461
`This lets you handle multiple requests without bugs.`,
4462
],
4463
},
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
+ },
4510
],
4511
};
4512
packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js
+10
@@ -401,6 +401,16 @@ export default {
401
});
402
}
403
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
+
414
// Add the dependency to a map so we can make sure it is referenced
415
// again in our dependencies array. Remember whether it's static.
416
if (!dependencies.has(dependency)) {