Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ESLint] Enforce deps array in useMemo and useCallback #15025

Merged
merged 1 commit into from
Mar 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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