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

前端 未结 2 1076
半阙折子戏
半阙折子戏 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 04:55

    Extract this logic to a component

    function Item({ item, isSharedItem }) {
      const company = useGetCompanyByItemId(item.id);
      return (
        <>
          {isSharedItem && (
            <div>
              <span>company</span>
            </div>
          )}
        </>
      );
    }
    

    and then use it in your loop

    springProps.map((index) => {
      ...
      return <Item item={item} isSharedItem={isSharedItem} key={index} />
    
    0 讨论(0)
  • 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 && 
              (<div>
                 <span>{company}</span>
               </div>)
          }
          </>);
    }
    

    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).
    0 讨论(0)
提交回复
热议问题