From cd4a2578ec8cc0e681bf838bd66fbe5616c4ad47 Mon Sep 17 00:00:00 2001 From: Rohit Patil Date: Tue, 27 Jun 2023 20:11:54 +0530 Subject: [PATCH] no react hook import within conditionals --- custom-rules.js | 1 + packages/eslint/index.js | 2 ++ packages/eslint/no_hook_conditional_import.js | 32 +++++++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 packages/eslint/no_hook_conditional_import.js diff --git a/custom-rules.js b/custom-rules.js index 78d78c1..9d42aa7 100644 --- a/custom-rules.js +++ b/custom-rules.js @@ -28,5 +28,6 @@ module.exports = { 'custom-rules/hook-sequence' : 'warn', 'custom-rules/variable-name-check' : 'warn', 'custom-rules/component-pascal-props' : 'warn', + 'custom-rules/no-hook-conditional-import' : 'warn', }, }; diff --git a/packages/eslint/index.js b/packages/eslint/index.js index 7f496d5..f100599 100644 --- a/packages/eslint/index.js +++ b/packages/eslint/index.js @@ -11,6 +11,7 @@ const is_empty_use_check = require('./is_empty_use_check'); const key_as_function = require('./key_as_function'); const key_in_for_each_map = require('./key_in_for_each_map'); const nbsp_ensp_check = require('./nbsp_ensp_check'); +const no_hook_conditional_import = require('./no_hook_conditional_import'); const regex_check = require('./regex_check'); const uuid_check = require('./uuid_check'); const variable_name_check = require('./variable_name_check'); @@ -35,5 +36,6 @@ module.exports = { 'hook-sequence' : hook_sequence, 'variable-name-check' : variable_name_check, 'component-pascal-props' : component_pascal_props, + 'no-hook-conditional-import' : no_hook_conditional_import, }, }; diff --git a/packages/eslint/no_hook_conditional_import.js b/packages/eslint/no_hook_conditional_import.js new file mode 100644 index 0000000..f62034b --- /dev/null +++ b/packages/eslint/no_hook_conditional_import.js @@ -0,0 +1,32 @@ +module.exports = { + meta: { + type : 'warn', + docs : { + description : 'Disallow react hooks in conditional statements', + category : 'Best Practices', + recommended : true, + }, + schema: [], + }, + + create(context) { + return { + CallExpression(node) { + const { callee = {} } = node || {}; + const { name = '' } = callee || {}; + if (name.startsWith('use')) { + const ancestors = context.getAncestors(); + const isCondition = ancestors.some((ancestor) => ( + ancestor.type === 'IfStatement' || ancestor.type === 'FunctionDeclaration' + )); + if (isCondition) { + context.report({ + node, + message: 'Do not use react hooks in conditional statements', + }); + } + } + }, + }; + }, +};