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

feature/no-unstable-dependencies #12

Merged
merged 4 commits into from
Jun 3, 2022
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ module.exports = {
| [private-component-methods](/docs/private-component-methods.md) | ✅ | 🔧 | Requires that all methods of react components are private (except reserved lifecycle methods) |
| [no-unhandled-scheduling](/docs/no-unhandled-scheduling.md) | ✅ | | `setTimeout` and `setInterval` calls should be cleared |
| [unregister-events](/docs/unregister-events.md) | ✅ | | Ensures all events registered in React components are unregistered when component unmounts |
| [no-unstable-dependencies](/docs/no-unstable-dependencies.md) | ✅ | | Helps find dependencies that are used in React hook dependency arrays that will change values every time the component render is called |

## LICENSE

Expand Down
65 changes: 65 additions & 0 deletions docs/no-unstable-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Prevents the use of variables with unstable values in React hook dependencies (`no-unstable-dependencies`)

Unstable dependencies should be avoided in React hook dependency arrays. This rule helps find dependencies that are used in React hook dependency arrays
that will change values every time the component render is called, such as when they are set to a new instance of an object, array, or function.

## Rule Details

Examples of **incorrect** code for this rule:

```typescript
class MyClass {}
const MyBadComponent: React.FC<any> = ({myInstance = new MyClass()}) => {
React.useEffect(() => {}, [myInstance]);
}

const MyBadComponent2: React.FC<any> = ({myObject = {}}) => {
React.useEffect(() => {}, [myObject]);
}

const MyBadComponent3: React.FC<any> = ({myArray = []}) => {
React.useEffect(() => {}, [myArray]);
}

const MyBadComponent4: React.FC<any> = () => {
const myFunction = () => {
alert("Hello");
};
React.useEffect(() => {}, [myFunction]);
}
```

Examples of **correct** code for this rule:

```typescript
class MyClass {}
const defaultInstance = new MyClass();
const MyGoodComponent: React.FC<any> = ({myInstance = defaultInstance}) => {
React.useEffect(() => {}, [myInstance]);
}

const defaultObject = {};
const MyGoodComponent2: React.FC<any> = ({myObject = defaultObject}) => {
React.useEffect(() => {}, [myObject]);
}

const defaultArray = [];
const MyGoodComponent3: React.FC<any> = ({myArray = defaultArray}) => {
React.useEffect(() => {}, [myArray]);
}

const MyGoodComponent4: React.FC<any> = () => {
const myFunction = React.useMemo(() => {

});
React.useEffect(() => {}, [myFunction]);
}
```

## When Not To Use It

False positives, or when constant/stable values in things like parameter defaults are not desired.

## Auto-fixable?

No ❌
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import noHrefAssignment from "./rules/no-href-assignment";
import noUnhandledScheduling from "./rules/no-unhandled-scheduling";
import privateComponentMethods from "./rules/private-component-methods";
import unregisterEvents from "./rules/unregister-events";
import noUnstableDependencies from "./rules/no-unstable-dependencies";

export = {
rules: {
"no-href-assignment": noHrefAssignment,
"private-component-methods": privateComponentMethods,
"no-unhandled-scheduling": noUnhandledScheduling,
"unregister-events": unregisterEvents,
"no-unstable-dependencies": noUnstableDependencies,
},
configs: {
recommended: {
Expand All @@ -18,6 +20,7 @@ export = {
"enterprise-extras/private-component-methods": "error",
"enterprise-extras/no-unhandled-scheduling": "warn",
"enterprise-extras/unregister-events": "error",
"enterprise-extras/no-unstable-dependencies": "warn",
},
},
all: {
Expand All @@ -27,6 +30,7 @@ export = {
"enterprise-extras/private-component-methods": "error",
"enterprise-extras/no-unhandled-scheduling": "error",
"enterprise-extras/unregister-events": "error",
"enterprise-extras/no-unstable-dependencies": "error",
},
},
},
Expand Down
94 changes: 94 additions & 0 deletions src/rules/no-unstable-dependencies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { ESLintUtils, TSESTree } from "@typescript-eslint/utils";
import {
isFunctionDeclaration,
isIdentifier,
isMemberExpression,
isMethod,
isUnstableAssignment,
isUnstableExpression,
} from "../utils/type-guards";

type MessageIds = "unstableDependency";
type Options = [];

const hooksWithDependenciesRegex = "use(Callback|Memo|Effect)";

export default ESLintUtils.RuleCreator(
(name) =>
`https://github.com/buildertrend/eslint-plugin-enterprise-extras/blob/main/docs/${name}.md`
)<Options, MessageIds>({
name: "no-unstable-dependencies",
meta: {
type: "suggestion",
fixable: "code",
docs: {
recommended: "error",
description:
"Unstable dependencies should be avoided in React hook dependency arrays",
},
messages: {
unstableDependency:
"Variable is created every render, but it is used in a React hook dependency array. Consider moving the value to a module constant.",
},
schema: [],
},
defaultOptions: [],
create: function (context) {
const reportUnstableDeps = (useHookCall: TSESTree.CallExpression) => {
if (useHookCall.arguments[1].type === "ArrayExpression") {
const scope = context.getScope();

useHookCall.arguments[1].elements.forEach((dependency) => {
if (isIdentifier(dependency)) {
const depReference = scope.references.find(
(ref) => ref.identifier === dependency
);

if (depReference) {
const depReferenceScope = depReference.from;

if (isFunctionDeclaration(depReferenceScope.block)) {
const depReferenceDefinitions = depReference.resolved?.defs;
if (
depReferenceDefinitions &&
depReferenceDefinitions.length > 0
) {
const writeReferences = depReference.resolved?.references
.filter((ref) => ref.isWrite() && ref.writeExpr)
.map((ref) => ref.writeExpr);

// If every known write expression is unstable, then we know that the variable is not save to use as a react hook dependency
if (
writeReferences &&
writeReferences.length > 0 &&
writeReferences.every((writeReference) =>
isUnstableExpression(writeReference!)
)
) {
writeReferences.forEach((writeReference) => {
context.report({
node: writeReference!,
messageId: "unstableDependency",
});
});
context.report({
node: dependency,
messageId: "unstableDependency",
});
}
}
}
}
}
});
}
};

return {
[`CallExpression[arguments.length>=2][callee.type="MemberExpression"][callee.property.type="Identifier"][callee.property.name=/${hooksWithDependenciesRegex}/]`]:
reportUnstableDeps,
[`CallExpression[arguments.length>=2][callee.type="Identifier"][callee.name=/${hooksWithDependenciesRegex}/]`]:
reportUnstableDeps,
};
},
});
61 changes: 61 additions & 0 deletions src/utils/type-guards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,75 @@ export const isMethod = (
);
};

export const isFunctionDeclaration = (
node: TSESTree.Node
): node is TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration => {
return (
node.type === "ArrowFunctionExpression" ||
node.type === "FunctionDeclaration"
);
};

export const isIdentifier = (
node: TSESTree.Expression | TSESTree.PrivateIdentifier
): node is TSESTree.Identifier => {
return node.type === "Identifier";
};

export const isMemberExpression = (
node: TSESTree.Expression
): node is TSESTree.MemberExpression => {
return node.type === "MemberExpression";
};

export const isAsExpression = (
node: TSESTree.Expression
): node is TSESTree.TSAsExpression => {
return node.type === "TSAsExpression";
};

const setOfUnstableAssignmentTypes = new Set([
"NewExpression",
"ObjectExpression",
"ArrayExpression",
"ArrowFunctionExpression",
"FunctionExpression",
"JSXElement",
"JSXFragment",
]);
type UnstableExpression =
| TSESTree.NewExpression
| TSESTree.ObjectExpression
| TSESTree.ArrayExpression
| TSESTree.ArrowFunctionExpression
| TSESTree.FunctionExpression
| TSESTree.JSXElement
| TSESTree.JSXFragment;
export const isUnstableExpression = (
node: TSESTree.Node
): node is UnstableExpression => {
return setOfUnstableAssignmentTypes.has(node.type);
};

export const isAssignmentPattern = (
node: TSESTree.Node
): node is TSESTree.AssignmentPattern => {
return node.type === "AssignmentPattern";
};

export const isVariableDeclarator = (
node: TSESTree.Node
): node is TSESTree.VariableDeclarator => {
return node.type === "VariableDeclarator";
};

export const isUnstableAssignment = (node: TSESTree.Node) => {
let expression: null | TSESTree.Expression = null;
if (isAssignmentPattern(node)) {
expression = node.right;
} else if (isVariableDeclarator(node)) {
expression = node.init;
}

return expression && isUnstableExpression(expression);
};
Loading