1

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

  • 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.

1
  • Please see this and this Commented Mar 25, 2020 at 17:18

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.