|
| 1 | +import type { Rule } from "eslint"; |
| 2 | +import type { ImportDeclaration, CallExpression, Property } from "estree"; |
| 3 | + |
| 4 | +// Custom Rule: No Import of useIsFocused from @react-navigation/native |
| 5 | +export const noUseIsFocusedImportRule: Rule.RuleModule = { |
| 6 | + meta: { |
| 7 | + type: "problem", |
| 8 | + docs: { |
| 9 | + description: |
| 10 | + "Disallow importing `useIsFocused` from `@react-navigation/native` to encourage using `useFocusEffect` instead.", |
| 11 | + category: "Best Practices", |
| 12 | + recommended: true, |
| 13 | + url: "https://github.com/bamlab/react-native-project-config/tree/main/packages/eslint-plugin/docs/rules/no-use-is-focused.md", |
| 14 | + }, |
| 15 | + messages: { |
| 16 | + noUseIsFocusedImport: |
| 17 | + "Please use 'useFocusEffect' instead of 'useIsFocused' to avoid excessive rerenders: 'useIsFocused' will trigger rerender both when the page goes in and out of focus.", |
| 18 | + }, |
| 19 | + schema: [], |
| 20 | + fixable: "code", |
| 21 | + }, |
| 22 | + |
| 23 | + create(context) { |
| 24 | + return { |
| 25 | + ImportDeclaration(node: ImportDeclaration) { |
| 26 | + if (node.source.value === "@react-navigation/native") { |
| 27 | + node.specifiers.forEach((specifier) => { |
| 28 | + if ( |
| 29 | + specifier.type === "ImportSpecifier" && |
| 30 | + specifier.imported.name === "useIsFocused" |
| 31 | + ) { |
| 32 | + context.report({ |
| 33 | + node: specifier, |
| 34 | + messageId: "noUseIsFocusedImport", |
| 35 | + }); |
| 36 | + } |
| 37 | + }); |
| 38 | + } |
| 39 | + }, |
| 40 | + CallExpression(node: CallExpression) { |
| 41 | + if ( |
| 42 | + node.callee.type === "Identifier" && |
| 43 | + node.callee.name === "require" && |
| 44 | + node.arguments.length > 0 && |
| 45 | + node.arguments[0].type === "Literal" && |
| 46 | + node.arguments[0].value === "@react-navigation/native" |
| 47 | + ) { |
| 48 | + const ancestors = context.getAncestors(); |
| 49 | + const parent = ancestors[ancestors.length - 1]; // Get the direct parent of the node |
| 50 | + |
| 51 | + if ( |
| 52 | + parent.type === "VariableDeclarator" && |
| 53 | + parent.id.type === "ObjectPattern" |
| 54 | + ) { |
| 55 | + const properties = parent.id.properties as Property[]; |
| 56 | + const useIsFocusedProperty = properties.find( |
| 57 | + (prop) => |
| 58 | + prop.type === "Property" && |
| 59 | + prop.key.type === "Identifier" && |
| 60 | + prop.key.name === "useIsFocused", |
| 61 | + ); |
| 62 | + |
| 63 | + if (useIsFocusedProperty) { |
| 64 | + context.report({ |
| 65 | + node: useIsFocusedProperty, |
| 66 | + messageId: "noUseIsFocusedImport", |
| 67 | + }); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + }, |
| 72 | + }; |
| 73 | + }, |
| 74 | +}; |
0 commit comments