4

As described here, when using hooks in a react library, you often encounter a react error saying hooks can only be called inside the body of a function component The most likely cause for this error is that your library links to its own react package and you main app also, so you end up using 2 different copies of the react package.

One typical solution to this error is to make sure you main app AND your library use the exact same react package.

The solution I use, is to:

  • cd to myMainApp/node_modules/react
  • yarn link
  • cd to myLib
  • yarn link react

This solution works. My main app and my library now use the same react package.

But what if I have multiple main apps? Let's say I have this project structure:

mainApp1 using lib1-1 and lib1-2

mainApp2 using lib2-1 and lib2-2

Both main apps are independent of each other. So lib1-1 and lib1-2 should link to the react package of mainApp1 and lib2-1 and lib2-2 should both link to the react package of mainApp2

How do I do that? When I try to run yarn link in mainApp2/node_modules/react, yarn tells me that there is already a link for react.

Unfortunately, I cannot use yarn link as react2 or something similar.

Any ideas on how to overcome this?

Note: this problem can be overcome by building your library (where react is a devDependency), committing your changes to git after every tweak and than upgrade the library in your main app. But off course, this is not a solution since during developing, you want to link to you libraries instead of re-importing them from the repo's

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Dany Dhondt
  • 881
  • 9
  • 27

2 Answers2

1

You can install react and react-dom globally, then link all of your projects to the global instance.

The procedure would be similar to the one you're using already, but creating symlinks to the global locations:

yarn global add react
yarn global add react-dom

Then you can link to them from your individual projects.

Will Jenkins
  • 9,507
  • 1
  • 27
  • 46
  • I always start new projects by running `npx create-react-app myApp` so would your solution be compatible with this workflow? – Dany Dhondt Oct 21 '19 at 08:44
  • ok, interesting thought. But this means that may top level app has to link to the global react package. Are there no caveats? Will react properly bundle with my app when building a production build? – Dany Dhondt Oct 21 '19 at 09:12
  • Yes, the bundling will ignore the global links and bring in the packages as normal. – Will Jenkins Oct 21 '19 at 09:14
  • A little bit off-topic but running `yarn global add react` gives me a `"react@16.10.2" has no binaries` warning – Dany Dhondt Oct 21 '19 at 09:35
  • https://stackoverflow.com/questions/40317578/yarn-global-command-not-working ? – Will Jenkins Oct 21 '19 at 09:58
1

if you are using a custom Webpack then you have to mention to use react from your node_modules.

resolve: {
    alias: {
        react: path.resolve('./node_modules/react'),
    },
}