The Story of Rules of Hooks

Learn about the rules of React Hooks and what to do when encountering an invalid hook call warning.

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 current rendering context to work which is not available outside React components.

Get hands-on with 1200+ tech skills courses.