React question detail
How to ensure hooks followed the rules in your project?
React team released an ESLint plugin called eslint-plugin-react-hooks that enforces Hook's two rules. It is part of Hooks API. You can add this plugin to your project using the below command,
npm install eslint-plugin-react-hooks --save-dev
And apply the below config in your ESLint config file,
// Your ESLint configuration
{
"plugins": [
// ...
"react-hooks"
],
"rules": {
// ...
"react-hooks/rules-of-hooks": "error"
}
}
This plugin also provide another important rule through react-hooks/exhaustive-deps. It ensures that the dependencies of useEffect, useCallback, and useMemo hooks are correctly listed to avoid potential bugs.
useEffect(() => {
// Forgetting `message` will result in incorrect behavior
console.log(message);
}, []); // Here `message` should be a dependency
The recommended eslint-config-react-app preset already includes the hooks rules of this plugin.
For example, the linter enforce proper naming convention for hooks. If you rename your custom hooks which as prefix "use" to something else then linter won't allow you to call built-in hooks such as useState, useEffect etc inside of your custom hook anymore.
Note: This plugin is intended to use in Create React App by default.