diff --git a/packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.js b/packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.js index a1e4c49e15573..4376d01d824a8 100644 --- a/packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.js +++ b/packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.js @@ -755,6 +755,30 @@ const tests = { `, errors: [loopError('useHookInsideLoop')], }, + { + code: normalizeIndent` + // Invalid because it's dangerous and might not warn otherwise. + // This *must* be invalid. + function ComponentWithHookInsideLoop() { + do { + useHookInsideLoop(); + } while (cond); + } + `, + errors: [loopError('useHookInsideLoop')], + }, + { + code: normalizeIndent` + // Invalid because it's dangerous and might not warn otherwise. + // This *must* be invalid. + function ComponentWithHookInsideLoop() { + do { + foo(); + } while (useHookInsideLoop()); + } + `, + errors: [loopError('useHookInsideLoop')], + }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. @@ -853,6 +877,45 @@ const tests = { `, errors: [loopError('useHook1'), loopError('useHook2', true)], }, + { + code: normalizeIndent` + // Invalid because it's dangerous and might not warn otherwise. + // This *must* be invalid. + function useHookInLoops() { + do { + useHook1(); + if (a) return; + useHook2(); + } while (b); + + do { + useHook3(); + if (c) return; + useHook4(); + } while (d) + } + `, + errors: [ + loopError('useHook1'), + loopError('useHook2'), + loopError('useHook3'), + loopError('useHook4'), + ], + }, + { + code: normalizeIndent` + // Invalid because it's dangerous and might not warn otherwise. + // This *must* be invalid. + function useHookInLoops() { + do { + useHook1(); + if (a) continue; + useHook2(); + } while (b); + } + `, + errors: [loopError('useHook1'), loopError('useHook2', true)], + }, { code: normalizeIndent` // Invalid because it's dangerous and might not warn otherwise. diff --git a/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js b/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js index 97e72f01e4ada..0b89390898ef4 100644 --- a/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js +++ b/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js @@ -295,7 +295,7 @@ export default { if (pathList.has(segment.id)) { const pathArray = Array.from(pathList); const cyclicSegments = pathArray.slice( - pathArray.indexOf(segment.id) + 1, + pathArray.indexOf(segment.id) - 1, ); for (const cyclicSegment of cyclicSegments) { cyclic.add(cyclicSegment);