From 2ed38d1885d885e3e4161ac2f28dab5006c087f3 Mon Sep 17 00:00:00 2001 From: Tianyu Yao Date: Mon, 5 Jun 2023 16:36:51 -0700 Subject: [PATCH] Warn about conditionally calling hooks when a hook call is an OptionalCallExpression --- .../__tests__/ESLintRulesOfHooks-test.js | 10 ++++++++++ packages/eslint-plugin-react-hooks/src/RulesOfHooks.js | 10 +++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.js b/packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.js index 7b90afb75a..8dbb24ee37 100644 --- a/packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.js +++ b/packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.js @@ -594,6 +594,16 @@ const tests = { `, errors: [conditionalError('useTernaryHook')], }, + { + code: normalizeIndent` + // Invalid because it's dangerous and might not warn otherwise. + // This *must* be invalid. + function ComponentWithOptionalChainingHook() { + useHook?.(); + } + `, + errors: [conditionalError('useHook')], + }, { code: normalizeIndent` // Invalid because it's a common misunderstanding. diff --git a/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js b/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js index e6a71cec11..d078a7661d 100644 --- a/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js +++ b/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js @@ -556,7 +556,7 @@ export default { // `CallExpression`s and check that _every use_ of a hook name is valid. // But that gets complicated and enters type-system territory, so we're // only being strict about hook calls for now. - CallExpression(node) { + 'CallExpression, OptionalCallExpression'(node) { if (isHook(node.callee)) { // Add the hook node to a map keyed by the code path segment. We will // do full code path analysis at the end of our code path. @@ -568,6 +568,14 @@ export default { reactHooksMap.set(codePathSegment, reactHooks); } reactHooks.push(node.callee); + + if (node.optional) { + const message = + `React Hook "${context.getSource(node.callee)}" is called ` + + 'conditionally. React Hooks must be called in the exact ' + + 'same order in every component render.'; + context.report({node, message}); + } } // useEffectEvent: useEffectEvent functions can be passed by reference within useEffect as well as in