create-react-app: Duplicate React

“Duplicate React” is an incredibly common issue that produces weird errors and confuses beginners and advanced users alike. It happens when you install react but some component you’re using installs its own copy of react (often with a different version).

React doesn’t throw in such cases because there are situations in which multiple React may validly coexist in the page (e.g. a third-party React-powered widget on a React-powered website). However it seems to make much less sense inside a single bundle. Webpack is in a perfect position to do this, but of course it won’t add any library-specific code. The good news is that we’re on top of webpack, so we might be able to do something.

There are several possible options:

    1. Do nothing. (Like now)
    1. Warn/error on duplicate React in the bundle.
    1. Alias React to always be the one on the top level, regardless of Node resolution mechanism.

Option (3) seems like the easiest to do (we can special-case React in our Webpack, and maybe Jest, configs). It also “just works” from the user’s point of view because they don’t need to delete any node_modules or mess with projects’ peerDependencies. The downside is the ecosystem loses because project authors don’t become aware that their components incorrectly depend on React, or that their components are outdated.

Option (2) seems like more work. It’s not immediately clear what message we could provide. Would we tell the user to delete the extra react from the respective node_modules subfolder? Would we tell them to file an issue with that component or library?

Finally, we could stick with doing nothing. Any thoughts?

About this issue

  • Original URL
  • State: open
  • Created 8 years ago
  • Reactions: 10
  • Comments: 15 (8 by maintainers)

Commits related to this issue

Most upvoted comments

I think this doesn’t only apply to React. Already had some troubles with duplicate dependencies in my bundle and I would love the bundler to tell me when that happens / allow me to prevent it. This is especially a problem when using npm link to link multiple private dependencies

@gaearon I can do it

Apparently Yarn has a resolutions field that let’s you declare what version to use inside package.json.

It also can guide you through the selection process with yarn install --flat .

Works like a charm and it is the right place to handle this kind of issues.

Not sure if NPM has anything of the same.

PR #2011 should solve this issue.

In my experience, option 3 is the most appropriate for a Webpack-based bundle. Any react-based dependency that doesn’t properly express a react peerDependency probably isn’t worth depending on in the first place. Another “duplicate react” trigger is using npm link with a dependent that has react as a devDependency (i.e., has a proper peerDependency); option 3 is the only solution for that problem AFAIK.