score:3

Accepted answer

This plugin does what you are asking for. However a word of caution.

https://www.npmjs.com/package/eslint-plugin-no-unused-react-component-methods

Currently it is impossible to simply have a parser that would check for unused component properties, because component properties can be called dynamically.

For example:

class Sample extends Component {
    // Plugin falsely flags this as unused.
    unUsedMethod() {
        console.log('I am used dynamically');
    }
    render() {
        // No way to parse dynamic function calls reliably
        this['unUsedMethod']();
        return 'Hello!';
    }
}

It also wouldn't work with react-onclickoutside package, as it requires a function to be attached to the component, that is called by wrapping the component in a HOC. https://www.npmjs.com/package/react-onclickoutside

Still the plugin helped me find a few unused functions, so it is worth a try in my opinion.

First install the package: npm i eslint-plugin-no-unused-react-component-methods --save-dev

Add "no-unused-react-component-methods" to your eslint configuration in the plugins section:

{
    "plugins": [
        "no-unused-react-component-methods"
    ],
}

And add into the rules section

{
    "rules": {
        "no-unused-react-component-methods/no-unused-react-component-methods": 2,
    }
}

So your config would look like:

{
  "parser": "babel-eslint",
  "env": {
    "browser": true,
    "es6": true,
    "node": true
  },
  "extends": ["eslint:recommended", "plugin:react/recommended"],
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true,
      "sourceType": "module",
      "allowImportExportEverywhere": false,
      "codeFrame": false
    },
    "sourceType": "module"
  },
  "plugins": [
    "react",
    "no-unused-react-component-methods"
  ],
  "rules": {
    "no-unused-react-component-methods/no-unused-react-component-methods": 2,
    "indent": [2, 4, { "SwitchCase": 1, "ObjectExpression": "first" }],
    "linebreak-style": ["error", "unix"],
    "semi": ["error", "always"],
    "react/display-name": 0,
    "react/prop-types": 0, // Temporary
    "react/no-unescaped-entities": 0,
    "no-trailing-spaces": 1
  }
}

Now it should highlight any seemingly unused functions! Let me know if it works or not.


Related Query

More Query from same tag