Ad

Eslint Vscode Plugin Is Not Producing Warnings For Hooks

I created a react app with npx create-react-app my-app and did a yarn install. Added the following to App.js:

const a = () => 1,
  b = () => 2,
  c = () => 3;

function App() {
  const wut = useMemo(() => {
    return { a: a(), b: b(), c: c() };
  }, [a]);
  useEffect(() => {
    console.log(a(), b(), c());
  }, [a]);

Yarn start will give me warnings but vscode does not.

I added .eslintrc.js with the following content:

module.exports = {
  env: {
    browser: true,
    es6: true
  },
  extends: ["eslint:recommended", "plugin:react/recommended"],
  globals: {
    Atomics: "readonly",
    SharedArrayBuffer: "readonly"
  },
  parserOptions: {
    ecmaFeatures: {
      jsx: true
    },
    ecmaVersion: 2018,
    sourceType: "module"
  },
  plugins: ["react"],
  rules: {
    "react/prop-types": [0],
    "no-console": [0],
    "react-hooks/exhaustive-deps": "warn"
  }
};
Ad

Answer

If I have the following code in a clean create-react-app:

function App(props) {
  const {a,b,c}=props;
  const wut = useMemo(() => {
    console.log("this should not happen multiple times");
    return { a: a(), b: b(), c: c() };
  }, [a]);
  useEffect(() => {
    console.log(a(), b(), c());
  }, [a]);

Then removing the .eslintrc.js would give me the React Hook useMemo has missing dependencies: warning and the option to auto fix it.

When I have the .eslintrc.js in project root directory I get the error Definition for rule 'react-hooks/exhaustive-deps' was not found. this is because the .eslintrc.js was missing a plugin and plugins: ["react", "react-hooks"], solved it.

However; now the rule is off by default so it won't warn, needed to explicitly add the rule and set it to warn (or error) in the .eslintrc.js:

  rules: {
    "react-hooks/exhaustive-deps": "error"
  }
Ad
source: stackoverflow.com
Ad