React JS: Rules of Hooks
ReactJS Rules of Hooks
📘 Rules of Hooks
Hooks
are a new addition in React 16.8
. They let you use state and other React features without writing a class.
Reference: Rules of Hooks
1 Overview
Hooks
are JavaScript functions, but you need to follow two rules when using them. We provide a linter plugin to enforce these rules automatically:
1.1 Rule #1: Only Call Hooks at the Top Level
Don’t call Hooks inside loops, conditions, or nested functions.
Instead, always use Hooks at the top level of your React function, before any early returns.
By following this rule, you ensure that Hooks are called in the same order each time a component renders.
That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
1.2 Rule #2: Only Call Hooks from React Functions
Don’t call Hooks from regular JavaScript functions. Instead, you can:
- Call
Hooks
from React function components. - Call
Hooks
from custom Hooks
(we’ll learn about them on the next page).
2 ESLint Plugin
React team released an ESLint plugin
called eslint-plugin-react-hooks
that enforces these two rules. You can add this plugin to your project if you’d like to try it:
This plugin is included by default in Create React App.