'Gatsby: Multiple usage of Custom-Hook leads to "Invalid hook call"

I'm trying to use a custom hook to insert some external JS into my Gatsby-Site that's used for some widgets (the JS manipulates the DOM, so that's the only way I found working so far)

Problem: Using the Code below, I can only use the "useScript-Hook" in one place without it throwing an error. As soon as I use it in multiple Places, it throws:

Invalid hook call. Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Even with the error, everything works fine, but I'm still confused why this is happening.

Here's my hook:

import * as React from "react"

const useScript = async (resourceUrl) => {
  React.useEffect(() => {
    const script = document.createElement("script")
    script.async = false
    script.defer = true
    script.src = resourceUrl
    document.body.appendChild(script)

    return () => {
      document.body.removeChild(script)
    }
  }, [resourceUrl])
}
export default useScript

The hook gets used in 2 different widget components

Widget 1:

import * as React from "react"
import useScript from "./useScript"

export default function Activecampaign() {
  useScript("https://xxxxx.activehosted.com/f/embed.php?id=5")
  return (
    <>
      <div class="_form_5"></div>
    </>
  )
}

and Widget 2:

import * as React from "react"
import useScript from "./useScript"

export default function ProvenExpert() {
  useScript(
    "https://www.provenexpert.com/widget/xxxxxx.js?feedback=1&avatar=1&competence=1&style=white"
  )
  return (
    <>
      <div id="pewl"></div>
    </>
  )
}

Those 2 widgets are then used in my Footer-Component.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source