How to fix the error “react use hook cannot be called inside a callback function” using react?

前端 未结 2 1103
半阙折子戏
半阙折子戏 2021-01-25 04:14

i am using useHook named useGetCompanyByItemId in the return statement.

and so i am getting the error "react hook cannot be called in a callback function"

<
2条回答
  •  自闭症患者
    2021-01-25 05:06

    I can see two ways of refactoring here:

    Option 1: If you dont have control over the custom hook to modify

    Extract the iteration into a component:

    const Company = ({itemId, isSharedItem}) => {
       const company = useGetCompanyByItemId(itemId);
       return (<>
          {isSharedItem && 
              (
    {company}
    ) } ); }

    Use the above component while you iterate.

    Option 2: If you have control over the custom hook: I would recommend to refactor custom hook to return a method than object. Sample usage:

    const {getCompanyByItemId} = useFetchCompany();

    . . .

    anywhere in the code, getCompanyByItemId(itemId)

    Obvious advantage with above option:

    • Readable and extendable and use it anywhere and even pass around
    • You don't have to worry about refactoring and code splitting just not to break hook rules(do so if it makes sense ofcourse).

提交回复
热议问题