Rules of Hooks
# 04. Rules of Hooks
Hooks are JavaScript functions, but you need to follow two rules when using them. We provide a linter plugin (opens new window) to enforce these rules:
# Only Call Hooks at the Top Level
Don't call Hooks inside loops, conditions, or nested functions. Ensure that Hooks are always called 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.
Tip
How does React know which state corresponds to which
useState? The answer is that React relies on the order in which Hooks are called.If we want to run an effect conditionally, we can put that condition inside our Hook:
useEffect(function persistForm() {
// Put the condition inside the effect
if (name !== '') {
localStorage.setItem('formData', name);
}
});
2
3
4
5
6
# 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
# ESLint Plugin
We released an ESLint plugin called eslint-plugin-react-hooks (opens new window) that enforces these two rules.
npm install eslint-plugin-react-hooks --save-dev
// Your ESLint configuration
{
"plugins": [
// ...
"react-hooks"
],
"rules": {
// ...
"react-hooks/rules-of-hooks": "error", // Checks rules of Hooks
"react-hooks/exhaustive-deps": "warn" // Checks effect dependencies
}
}
2
3
4
5
6
7
8
9
10
11
12