How to setup ESLint in React applications?

ESLint is very popular in the JavaScript World. It finds and fixes problems in JavaScript code.

What is ESLint?

ESLint parses the code, analyses it, and runs linting rules. These rules may trigger warnings or errors if the code is correct or wrong.

ESLint setup in React:

Let us consider that we have React application setup. We need to follow these steps to setup ESLint:

Step #1

Install ESLint using following command:

npm install eslint eslint-plugin-react --save-dev

# or

yarn add eslint eslint-plugin-react --dev

The above command will add the following two libraries under devDependencies like below:

  "devDependencies": {
    "eslint": "^7.32.0",  // The version might differ
    "eslint-plugin-react": "^7.26.1" // The version might differ
  }

Step #2

We need an ESLint configuration file. We can create the .eslintrc.json file using following command with --init flag:

$ npx eslint --init

# or

$ yarn run eslint --init

Once we run the command it will ask set of questions to create the config file. In our case the .eslintrc.json file had the following content:

{
    "env": {
        "browser": true,
        "es6": true
    },
    "extends": [
        "eslint:recommended", // https://github.com/eslint/eslint/blob/main/conf/eslint-recommended.js
        "plugin:react/recommended"
    ],
    "globals": {
        "Atomics": "readonly",
        "SharedArrayBuffer": "readonly"
    },
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": 2018,
        "sourceType": "module"
    },
    "plugins": [
        "react"
    ],
    "rules": {
        "object-curly-spacing": ["error", "always"],
        "prefer-const": ["error"],
        "quotes": ["error"]
    }
}

The rules will be empty initially but we can add as many rules as we want. The recommended rules can be found here:
https://github.com/eslint/eslint/blob/main/conf/eslint-recommended.js

Reference: