Skip to content

Commit

Permalink
[ESLint] Disallow hooks in async functions (#27045)
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
acdlite committed Jul 5, 2023
1 parent d8c7f59 commit f35b3c7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
2 changes: 1 addition & 1 deletion compiled/facebook-www/REVISION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
5c8dabf8864e1d826c831d6096b2dfa66309961a
7118f5dd7bf5f1c44d0d2944ef8ad58e423909ad
12 changes: 11 additions & 1 deletion compiled/facebook-www/eslint-plugin-react-hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -623,10 +623,20 @@ var RulesOfHooks = {


if (isDirectlyInsideComponentOrHook) {
// Report an error if a hook does not reach all finalizing code
// Report an error if the hook is called inside an async function.
var isAsyncFunction = codePathNode.async;

if (isAsyncFunction) {
context.report({
node: hook,
message: "React Hook \"" + context.getSource(hook) + "\" cannot be " + 'called in an async function.'
});
} // Report an error if a hook does not reach all finalizing code
// path segments.
//
// Special case when we think there might be an early return.


if (!cycled && pathsFromStartToEnd !== allPathsFromStartToEnd && !isUseIdentifier(hook) // `use(...)` can be called conditionally.
) {
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?' : '');
Expand Down

0 comments on commit f35b3c7

Please sign in to comment.