Rules of usage of Hooks ensure that react components are pure functions and that state update logic in a component is visible from its source code. You can only call Hooks while React is rendering a function component. To ensure this we follow two basic rules:
Do not call hooks in Class components Javascript functions, Event handlers and Callback functions
You can call Hooks from Functional components other custom Hooks
Hooks must be called in the same order on every render. This ensures that React maintains the proper association between state variables and hooks.
loops
conditions
nested functions
after a conditional return statement.
Do not call Hooks inside functions passed to useMemo, useReducer, or useEffect, as they use a set of dependencies to decide whether to execute or not
Instead, always use Hooks at the top level of your React function, before any early returns. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)