Hooks are an innovation in React that allows you to use state and other React features without writing classes.
Hooks are normal JavaScript functions, but there are two rules to follow. To apply them automatically, we’ve created a plugin for the linter:
Only use hooks at the top level.
Do not call hooks inside loops, conditional statements or nested functions. Instead, always use hooks only inside React functions, before returning any value from them. Enforcing this rule ensures that hooks are called in the same sequence every time a component is rendered. This will allow React to properly preserve the state of the hooks between multiple useState and useEffect calls. (If you’re interested, a detailed explanation below.)
Only call hooks from React functions
Do not call hooks from regular JavaScript functions. You can instead:
- Call hooks from a React function component.
- Call hooks from a custom hook (we’ll learn how to do this on the next page).
Following this rule ensures that all of the component’s state logic is clearly visible from the source code.
