Learn about the rules of React Hooks and what to do when encountering an invalid hook call warning.
Table of Contents
Rules for React Hooks
React requires you to follow some rules when calling React Hooks. These rules are important for React Hooks to function as expected. If one of the rules is not adhered to, React library will throw a runtime error known as Invalid Hook Call Warning
.
See the rules below:
1. Only call hooks at the top level
Hooks should only be called at the top level of a component.
Hooks should not be called in if
statements, loops, or nested functions. React Hooks such as useState
and useEffect
rely on the order in which they are called to preserve the current context and to calculate for the next state or side effect accordingly.
If the order of hook calls is different in each render, it would break this flow in React. For this reason, the first rule is very important.
2. Only call hooks from React functions
The second rule of React Hooks says that you should only call React Hooks from a React component. Hooks should not be called from plain JavaScript functions.
This rule should remind you that React Hooks need the current rendering context to work which is not available outside React components.
Q Can you call React hooks from a class component?
Answer in comments in end of post
Invalid Hook Call Warning
When beginning to use React Hooks, many developers run into this warning which is thrown by React on runtime. It usually means the code might be breaking one of the rules of hooks.
The obvious reasons behind this warning are:
- React Hooks were included outside React functions
- Trying to call hooks in an
if
statement
However, in some cases, the reason for this warning is not clear. Other reasons are mentioned below:
Mismatching React
Both React and the React DOM package versions should match exactly. Note that React Hooks are available in React 16.8 and above.
Duplicate React
Multiple copies of the React package in the same application will also cause an invalid hook call warning. This can be avoided in one of the following ways:
- Use
npm ls react
to find the duplicate React packages and only keep one. - Use Yarn resolutions to force a single version in the application.
- If using bundlers like webpack, define an
alias
to resolvereact
import to the React package innode_modules
of your main app.