Skip to content

Commit

Permalink
Enforce deps array in useMemo and useCallback (#15025)
Browse files Browse the repository at this point in the history
  • Loading branch information
gaearon authored Mar 6, 2019
1 parent a9aa24e commit 5d49daf
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,16 @@ const tests = {
}
`,
},
{
// Valid because they have meaning without deps.
code: `
function MyComponent(props) {
useEffect(() => {});
useLayoutEffect(() => {});
useImperativeHandle(props.innerRef, () => {});
}
`,
},
{
code: `
function MyComponent(props) {
Expand Down Expand Up @@ -924,6 +934,26 @@ const tests = {
'Either include it or remove the dependency array.',
],
},
{
// Invalid because they don't have a meaning without deps.
code: `
function MyComponent(props) {
const value = useMemo(() => { return 2*2; });
const fn = useCallback(() => { alert('foo'); });
}
`,
// We don't know what you meant.
output: `
function MyComponent(props) {
const value = useMemo(() => { return 2*2; });
const fn = useCallback(() => { alert('foo'); });
}
`,
errors: [
"React Hook useMemo doesn't serve any purpose without a dependency array as a second argument.",
"React Hook useCallback doesn't serve any purpose without a dependency array as a second argument.",
],
},
{
// Regression test
code: `
Expand Down
12 changes: 12 additions & 0 deletions packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,18 @@ export default {
const depsIndex = callbackIndex + 1;
const declaredDependenciesNode = node.parent.arguments[depsIndex];
if (!declaredDependenciesNode) {
// These are only used for optimization.
if (
reactiveHookName === 'useMemo' ||
reactiveHookName === 'useCallback'
) {
context.report({
node: node,
message:
`React Hook ${reactiveHookName} doesn't serve any purpose ` +
`without a dependency array as a second argument.`,
});
}
return;
}

Expand Down

0 comments on commit 5d49daf

Please sign in to comment.