Don't suggest a function as its own dep (#15115)

This commit is contained in:
Dan Abramov 2019-03-15 15:14:01 +00:00 committed by GitHub
parent 371bbf36bb
commit f1ff4348c1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 76 additions and 0 deletions

View File

@ -972,6 +972,26 @@ const tests = {
}
`,
},
{
code: `
function Example() {
const foo = useCallback(() => {
foo();
}, []);
}
`,
},
{
code: `
function Example({ prop }) {
const foo = useCallback(() => {
if (prop) {
foo();
}
}, [prop]);
}
`,
},
],
invalid: [
{
@ -4441,6 +4461,52 @@ const tests = {
`This lets you handle multiple requests without bugs.`,
],
},
{
code: `
function Example() {
const foo = useCallback(() => {
foo();
}, [foo]);
}
`,
output: `
function Example() {
const foo = useCallback(() => {
foo();
}, []);
}
`,
errors: [
"React Hook useCallback has an unnecessary dependency: 'foo'. " +
'Either exclude it or remove the dependency array.',
],
},
{
code: `
function Example({ prop }) {
const foo = useCallback(() => {
prop.hello(foo);
}, [foo]);
const bar = useCallback(() => {
foo();
}, [foo]);
}
`,
output: `
function Example({ prop }) {
const foo = useCallback(() => {
prop.hello(foo);
}, [prop]);
const bar = useCallback(() => {
foo();
}, [foo]);
}
`,
errors: [
"React Hook useCallback has a missing dependency: 'prop'. " +
'Either include it or remove the dependency array.',
],
},
],
};

View File

@ -401,6 +401,16 @@ export default {
});
}
// Ignore references to the function itself as it's not defined yet.
const def = reference.resolved.defs[0];
if (
def != null &&
def.node != null &&
def.node.init === node.parent
) {
continue;
}
// Add the dependency to a map so we can make sure it is referenced
// again in our dependencies array. Remember whether it's static.
if (!dependencies.has(dependency)) {