Skip to content

Commit f35b3c7

Browse files
committed
[ESLint] Disallow hooks in async functions (#27045)
Hooks cannot be called in async functions, on either the client or the server. This mistake sometimes happens when using Server Components, especially when refactoring a Server Component to a Client Component. React logs a warning at runtime, but it's even better to catch this with a lint rule since it will show immediate inline feedback in the editor. I added this to the existing "Rules of Hooks" ESLint rule. DiffTrain build for [7118f5d](7118f5d)
1 parent d8c7f59 commit f35b3c7

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

compiled/facebook-www/REVISION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
5c8dabf8864e1d826c831d6096b2dfa66309961a
1+
7118f5dd7bf5f1c44d0d2944ef8ad58e423909ad

compiled/facebook-www/eslint-plugin-react-hooks.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -623,10 +623,20 @@ var RulesOfHooks = {
623623

624624

625625
if (isDirectlyInsideComponentOrHook) {
626-
// Report an error if a hook does not reach all finalizing code
626+
// Report an error if the hook is called inside an async function.
627+
var isAsyncFunction = codePathNode.async;
628+
629+
if (isAsyncFunction) {
630+
context.report({
631+
node: hook,
632+
message: "React Hook \"" + context.getSource(hook) + "\" cannot be " + 'called in an async function.'
633+
});
634+
} // Report an error if a hook does not reach all finalizing code
627635
// path segments.
628636
//
629637
// Special case when we think there might be an early return.
638+
639+
630640
if (!cycled && pathsFromStartToEnd !== allPathsFromStartToEnd && !isUseIdentifier(hook) // `use(...)` can be called conditionally.
631641
) {
632642
var message = "React Hook \"" + context.getSource(hook) + "\" is called " + 'conditionally. React Hooks must be called in the exact ' + 'same order in every component render.' + (possiblyHasEarlyReturn ? ' Did you accidentally call a React Hook after an' + ' early return?' : '');

0 commit comments

Comments
 (0)