diff --git a/custom-rules.js b/custom-rules.js index 018a68b..c8bb67c 100644 --- a/custom-rules.js +++ b/custom-rules.js @@ -27,6 +27,7 @@ module.exports = { 'custom-rules/default-usestate' : 'warn', 'custom-rules/hook-sequence' : 'warn', 'custom-rules/variable-name-check' : 'warn', + 'custom-rules/no-hook-conditional-import' : 'warn', 'custom-rules/component-pascal' : 'warn', 'custom-rules/variable-value-jsx' : 'warn', 'custom-rules/default-component-props' : 'warn', diff --git a/packages/eslint/index.js b/packages/eslint/index.js index 6604554..4d8f291 100644 --- a/packages/eslint/index.js +++ b/packages/eslint/index.js @@ -12,6 +12,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'); @@ -36,6 +37,7 @@ module.exports = { 'default-usestate' : default_usestate, 'hook-sequence' : hook_sequence, 'variable-name-check' : variable_name_check, + 'no-hook-conditional-import' : no_hook_conditional_import, 'component-pascal' : component_pascal, 'variable-value-jsx' : variable_value_jsx, 'default-component-props' : default_comp_props, 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', + }); + } + } + }, + }; + }, +};