Error : Invalid Hook Call Warning Fix With Examples

Spread the love

There are three common reasons you might be seeing this warning:

  1. You might have mismatching versions of React and React DOM.
  2. You might be breaking the rules of Hooks
  3. Duplicate React (You might have more than one copy of React in the same app).

Let’s look at each of these cases.

  1. Mismatching Versions of React and React DOM
You might be using different version of react-dom or react-native that doesn’t support Hooks. check which version you are using by running npm ls react-dom or npm ls react-native in your application folder.
  1. Breaking the rules of Hooks
You can call Hooks while rendering a functional component only.
  • You should call them at the top level in the body of functional component.
  • You should call them at the top level in the body of custom Hooks.
function Timer() {
  //  Good: top-level in a function component
  const [time, setTime] = useState(0);
  // …
}
function useWindowWidth() {
  // Good: top-level in a custom Hook
  const [width, setWidth] = useState(window.innerWidth);
  // …
}
3.Duplicate React
You might see this waring if you have two copies of the react package in the same app. If you see more than one React, you’ll need to figure out why this happens and fix your dependency. 
You can also  this problem by ]debug, adding some logs and restarting your development server:
// Add this in node_modules/react-dom/index.js
window.React1 = require(‘react’);
// Add this in your component file
require(‘react-dom’);
window.React2 = require(‘react’);
console.log(window.React1 === window.React2);
If it prints false then you might have two Reacts and need to figure out why that happened.
This problem also comes when you use npm link or an equivalent. In that case, your might “see” two Reacts — one in application folder and one in your library folder. Assuming myapp and mylib are sibling folders, one possible fix is to run npm link ../myapp/node_modules/react from mylib. This should make the library use the application’s React copy.
admin

admin

Leave a Reply

Your email address will not be published.