I’m having trouble with my React setup. I’ve got a component library that I want to use in another project. It works fine when I publish it, but I wanted to make local development easier by using symlinks.
When I try to use npm link, I get errors about React hooks not working. It says something about not being able to read ‘useState’. I’ve tried to make sure both projects use the same React version (18.3.0), but it didn’t help.
I even tried removing React from the library and linking to the main project’s React. Still no luck. The error message suggests there might be multiple copies of React, but I can’t figure out how to fix it.
Has anyone dealt with this before? Is there a way to make symlinks work for local development of React component libraries? I’d rather not use a local registry if possible. It seems like overkill for what I’m trying to do.
Any tips or tricks would be really helpful. Thanks!
hey, i’ve run into this too. super annoying! have u tried using npm’s ‘overrides’ in ur package.json? it can force a single react version across everything. just add:
“overrides”: {
“react”: “$version”,
“react-dom”: “$version”
}
replace $version with ur react version. might solve it without changing ur setup much. good luck!
I’ve encountered this issue before, and it can be quite frustrating. The problem often stems from having multiple instances of React in your project, even when you think you’ve eliminated them. One solution that worked for me was using the ‘alias’ feature in webpack.
In your webpack config, add something like this:
resolve: {
alias: {
react: path.resolve('./node_modules/react'),
'react-dom': path.resolve('./node_modules/react-dom')
}
}
This forces webpack to use a single copy of React for both your main project and the linked library. It’s not foolproof, but it solved the hook errors in my case without needing to resort to a local registry or other complex setups.
Remember to clear your node_modules and reinstall after making these changes. It might take some tweaking, but it’s worth a shot if you’re set on using symlinks for development.
I’ve been down this road before, and it’s definitely a tricky one. One approach that’s worked well for me is using yarn workspaces instead of npm link. It manages dependencies more effectively and avoids the dreaded multiple React instances problem.
First, set up a root package.json with workspaces defined. Then, in your component library’s package.json, add a ‘main’ field pointing to the source, not the build. In your main project, reference the library using a relative path.
This setup lets you work on both projects simultaneously without publishing. It’s been a game-changer for my workflow, eliminating those pesky hook errors and saving time on builds during development.
If you’re committed to npm, another option is to use ‘npm pack’ to create a tarball of your library, then install that locally. It’s a bit more manual but can work in a pinch.