Invalid hook call. Hooks can only be called inside of the body of a function component

Topic summary

A developer is encountering a React hooks error while attempting to bulk update products. The code uses useCallback for a submitHandler function that iterates through products and calls a GraphQL mutation (updateProduct) to modify product titles and descriptions.

Technical Issue:

  • The mutation function runMutation is defined inside the callback but may be causing the hooks violation error
  • The code recursively calls runMutation to process products sequentially

Proposed Solution:

  • Wrap the runMutation function itself in useCallback
  • Pass [updateProduct, products] as dependencies to the hook

This should resolve the invalid hook call error by properly memoizing the nested function according to React’s Rules of Hooks.

Summarized with AI on November 22. AI used: claude-sonnet-4-5-20250929.
const submitHandler = useCallback(() => {
    let count = 0
    const runMutation = (product) => {
      updateProduct({
        variables: {
          input: {
            descriptionHtml: `${product.descriptionHtml}${descriptionValue}`,
            title: `${product.title}${titleValue}`,
            id: product.id
          }
        }
      }).then((data) => {
        console.log('Update product', count, data);
        count++;
        if(products[count]) runMutation(products[count])
        else {
          console.log('Update complete');
          setShowToast(true);
        }
      })
    }
    runMutation(products[count])
  
  }, [products, descriptionValue, titleValue]);

Wrap runMutation in useCallback, and pass [updateProduct, products] as the deps.

1 Like