Martin
Martin

Reputation: 726

Error when Using Custom React Hook in a Multi-Module Project for Tests with Jest

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:

  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

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

Upvotes: 1

Views: 673

Answers (1)

Martin
Martin

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

Related Questions