Enforcing the rules of Hooks
If we stick to the convention of prefixing Hook functions with use
, we can automatically enforce the other two rules:
- Only call Hooks from React function components
- Only call Hooks at the top level (not inside loops, conditions, or nested functions)
In order to enforce the rules automatically, React provides an ESLint plugin called eslint-plugin-react-hooks
, which will automatically detect when Hooks are used, and will ensure that the rules are not broken. ESLint is a linter, which is a tool that analyzes source code and finds problems such as stylistic errors, potential bugs, and programming errors.
Thankfully, Vite has already set up ESLint with the relevant React plugins for us. You may remember that in Chapter 2, Using the State Hook, we had to specifically disable the linter when we added a conditional Hook, by adding the following line:
// eslint-disable-next-line react-hooks/rules-of-hooks
If we removed this...