Sometimes, we may run into the ‘Invalid Hook Call Warning’ when we’re developing React apps.
In this article, we’ll look at how to fix the ‘Invalid Hook Call Warning’ when we’re developing React apps.
Fix the ‘Invalid Hook Call Warning’ When Developing React Apps
To fix the ‘Invalid Hook Call Warning’ when we’re developing React apps, we should only call hooks inside the body of function components.
To make sure that we can use hooks in React components, we should make sure we have React version 16.8 or higher.
Also, we should make sure that we’re mismatching versions of React and React DOM.
We should also not have more than one copy of React, which may create issues.
To check for multiple copies of React, we can run:
npm ls react
to check for multiple copies of the react
package.
The Rules of Hooks should be followed when we’re calling hooks if we eliminated the React version issues.
The first rule of hooks is that we should only call hooks at the top levels.
Hooks can’t be called inside loops conditions or nested functions since only calling hooks at the top level of a function component ensure that the hooks are called in the same order that they’re listed.
The other rule of hooks is that they can only be called from function components or custom hooks.
This way, we can ensure that logic can easily be reused in our React project.
To check for rule of hooks with ESLint, we can add:
{
"plugins": [
// ...
"react-hooks"
],
"rules": {
// ...
"react-hooks/rules-of-hooks": "error", // Checks rules of Hooks
"react-hooks/exhaustive-deps": "warn" // Checks effect dependencies
}
}
to .eslintrc
file.
Conclusion
To fix the ‘Invalid Hook Call Warning’ when we’re developing React apps, we should only call hooks inside the body of function components.
To make sure that we can use hooks in React components, we should make sure we have React version 16.8 or higher.
Also, we should make sure that we’re mismatching versions of React and React DOM.
The Rules of Hooks should be followed when we’re calling hooks if we eliminated the React version issues.