ReactJS – Invariant Violation due to refs or multiple copies of React

I am using ReactJS, with Gulp, Browserify, etc, all managed by NPM. I just updated my packages (npm update), but got the following error:

“Uncaught Invariant Violation: addComponentAsRefTo(…): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component’s `render` method, or you have multiple copies of React loaded (details:”

I was quite confused by this, as I am not using refs anywhere, and I thought NPM was meant to stop me from having multiple copies of things loaded. It turns out that isn’t the case – – and NPM is not great at deduplicating dependencies. Therefore, the update had introduced a second version of react (under material-ui), which was causing this error.

Thankfully the fix is pretty easy, and is now my standard NPM equivalent of switch it off and on again:

  • Delete the node_modules directory
  • Run npm install

This should give you a clean set of dependencies and no duplication of react. Of course, if you are using gulp or similar, remember to re-build your bundles before reloading your app to check that the error has gone away. This caused me a moment of frustration before I realised my schoolboy error!