Skip to content

Bug: Impossible to use on async hooks #21381

@arietrouw

Description

@arietrouw

The rule that prevents using async functions in the hook makes sense in most cases, but there are some valid hooks that have async functions. See useAsyncEffect as an example. (https://www.npmjs.com/package/use-async-effect)

Since the no async rule is bundled with the 'react-hooks/exhaustive-deps' rule, there is no way to use this with an async hook.

React version: 16, 17

Steps To Reproduce

  1. Create a file that uses useAsyncHook

  2. Configure plugin ->

    "react-hooks/exhaustive-deps": [
    "warn",
    {
    "additionalHooks": "(useAsyncEffect)"
    }
    ]

  3. lint - see error

The current behavior

linter displays:

warning Effect callbacks are synchronous to prevent race conditions. Put the async function inside:

useEffect(() => {
async function fetchData() {
// You can await here
const response = await MyAPI.getData(someId);
// ...
}
fetchData();
}, [someId]); // Or [] if effect doesn't need props or state

Learn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching react-hooks/exhaustive-deps

The expected behavior

Several options:

  1. Detect the proper use of async in the hook (may be tough)
  2. Make a "react-hooks/no-async" rule to control this behavior (allows exhaustive-dpes check w/o this warning)
  3. Add settings for the "additionalHooks" property to specify hook by hook functionality

I would say that all 3 of this would be great, but #2 to me seems to be a very simple fix.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions