Reputation: 726
I'm having a project with multiple Webpack modules. In my child module, I want to create a custom React hook, which I can use in React components in the parent module.
My example hook is quite simple:
export function useTitle(title: string): void {
useEffect(() => {
document.title = title
}, [title]);
}
However, when using my custom hook in a React component outside of the module, I get an error:
Error: 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:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app
I assume that the cause is that a React instance is created for each Webpack module. A Jest test comparing the React instance of the child module with the one of the parent module also shows this.
import {react} from "child-module";
test("react instance", () => {
expect(react).toBe(React); // serializes to the same string, but unequal
});
Is there anyway to use a custom React hook from one Webpack module in another without getting an error?
What I have already tried without any success
In my Webpack config files, I set external declarations for React to avoid that React will be included in the output Webpack bundles.
In the package.json of the child module, I have declare React as peer dependency.
In the package.json of the parent module, I have linked to the React installation of the child-module: "react": "../child-module/node_modules/react"
to ensure that both modules use the same React copy.
On runtime, I make it working my delivering React from a CDN and not from any Webpack module. However, it doesn't help me much if I cannot test my React components.
Upvotes: 1
Views: 673
Reputation: 726
I could finally solve the issue by storing React in the node_modules folder of the common root folder of the child and parent module.
My project structure:
project
|
+--- node_modules <-- React is here
|
+--+ child-module
| |
| +--- node_modules <-- Does NOT contain React
|
+--+ parent-module
|
+--- node_modules <-- Does NOT contain React
Upvotes: 1