Skip to content

Commit

Permalink
Don't suggest a function as its own dep (#15115)
Browse files Browse the repository at this point in the history
  • Loading branch information
gaearon authored Mar 15, 2019
1 parent 371bbf3 commit f1ff434
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
{
Expand Down Expand Up @@ -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.',
],
},
],
};

Expand Down
10 changes: 10 additions & 0 deletions packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down

0 comments on commit f1ff434

Please sign in to comment.