Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 132 ยท Testing and Quality

Linting, Formatting and Code Quality

Keep a React codebase healthy. Set up ESLint with the hooks rules, Prettier, strict TypeScript and pre-commit checks, then use naming rules, a review checklist and dependency hygiene.

A codebase is read far more often than it is written. Six months from now, you or a teammate will open a file at 5 p.m. on a Friday and need to understand it quickly. Code quality is everything that makes that easy: consistent formatting, names that say what things are, tools that catch mistakes before anyone runs the code, and small habits in review. None of it is glamorous, and all of it compounds.

The good news is that a lot of quality can be handed to machines. A formatter (Prettier) ends every argument about spaces and quotes. A linter (ESLint) catches bugs like a missing hook dependency while you type. A type checker (TypeScript) rejects wrong props before the browser sees them. Humans then spend their review time on design, naming and behaviour instead of commas. This lesson sets all of that up and adds the human parts: naming conventions, a review checklist and care for your dependencies. It continues from Debugging React Apps and leads into TypeScript and React.

Linters, formatters and npm run in your terminal and build pipeline, not in our browser editor. Configuration files in this lesson are therefore read-only. Where an idea can be shown with plain JavaScript, a live example runs.

Three tools, three jobs

Tool Question it answers Example finding
Formatter (Prettier, Biome) "How should this code look?" Wrap at 100 columns, single quotes, trailing commas
Linter (ESLint, Biome) "Is this code likely wrong or risky?" Hook inside a condition, unused variable, missing alt
Type checker (TypeScript) "Do these pieces fit together?" Passing a string where a number is required

Keep the jobs separate. A formatter has no opinions about correctness, a linter should not argue about indentation (turn off lint rules that clash with the formatter), and a type checker does not care about style. Each runs automatically: in your editor on save, in a pre-commit hook for the files you changed, and in CI for everyone (End-to-End and Accessibility Testing shows a pipeline).

ESLint for React (read-only)

ESLint parses your code into a syntax tree and runs rules over it. A rule is a small function that says "when you see this shape of code, report a problem". Projects created with Vite or Next.js already include a starter configuration. The modern format is a single flat config file:

JavaScript
// eslint.config.js (read-only: needs eslint, @eslint/js, eslint-plugin-react-hooks, eslint-plugin-jsx-a11y)
import js from '@eslint/js';
import reactHooks from 'eslint-plugin-react-hooks';
import jsxA11y from 'eslint-plugin-jsx-a11y';

export default [
  js.configs.recommended,
  {
    files: ['**/*.{js,jsx}'],
    languageOptions: {
      ecmaVersion: 'latest',
      sourceType: 'module',
      parserOptions: { ecmaFeatures: { jsx: true } },
    },
    plugins: { 'react-hooks': reactHooks, 'jsx-a11y': jsxA11y },
    rules: {
      'react-hooks/rules-of-hooks': 'error',
      'react-hooks/exhaustive-deps': 'warn',
      'jsx-a11y/alt-text': 'error',
      'jsx-a11y/label-has-associated-control': 'error',
      'no-unused-vars': ['error', { varsIgnorePattern: '^_' }],
    },
  },
];

Run it with npx eslint . and add a script to package.json: "lint": "eslint .". Newer versions of the React Hooks plugin also ship checks that go beyond the two rules above (for instance about mutating values during render, which the compiler relies on); read the plugin's documentation for its current presets rather than copying names from an old article.

The two rules you must never switch off

react-hooks/rules-of-hooks is an error. It reports hooks called inside conditions, loops, nested functions or after an early return, the bug behind Rendered more hooks than during the previous render (Rules of Hooks).

react-hooks/exhaustive-deps checks the dependency array of useEffect, useMemo and useCallback. If the function reads userId but the array does not list it, the rule warns. This catches stale closures, one of the most common causes of "my effect uses old data" (Effect Dependencies). When it complains, do not silence it with a disable comment. Ask why: usually the right fix is to move the value inside the effect, use an updater function, or extract the non-reactive part with useEffectEvent.

JSX
// What exhaustive-deps says about this code (read-only):
useEffect(() => {
  document.title = 'Hello, ' + name;
}, []);
// Warning: React Hook useEffect has a missing dependency: 'name'.
// Either include it or remove the dependency array.

An // eslint-disable-next-line is acceptable only with a comment explaining why it is safe. A bare disable is a bug you chose not to see.

Other worthwhile rules

  • jsx-a11y/* catches missing alt, unlabeled controls and clickable divs (Accessibility).
  • react/jsx-key (from eslint-plugin-react) reports a list without keys.
  • no-console set to warn stops debugging output from reaching production.
  • @typescript-eslint/* adds type-aware checks such as unhandled promises ("floating promises").

Start with a recommended preset and add rules only when a real bug or review comment justifies them. A config with 200 rules nobody understands gets ignored.

How a lint rule thinks

To see the idea, here is a miniature linter. Real ESLint walks a syntax tree; ours only runs regular expressions over source text, so it is fooled easily, which is itself the lesson. It scans three snippets for three smells: an array index used as a key, an effect with no dependency array, and dangerouslySetInnerHTML.

A mini linter built from regular expressions

The first two files are flagged correctly and Good.jsx is clean. But Comment.jsx is a false positive: the word only appears in a comment, and a regex cannot tell code from comments. The reverse can happen too (a rule that misses real problems). That is exactly why ESLint parses code into a tree: it knows what is an identifier, what is a string and what is a comment. When you write a custom rule for your team, write it against the syntax tree, never with regular expressions.

Prettier: stop arguing about style (read-only)

Prettier reads your code and prints it again in one canonical style, so every file looks as if one person wrote it. Almost nothing is configurable on purpose.

JSON
{
  "singleQuote": true,
  "semi": true,
  "printWidth": 100,
  "trailingComma": "all"
}

Save this as .prettierrc. Then npx prettier --write . formats the project, and npx prettier --check . fails when something is unformatted (use that one in CI). Turn on "format on save" in your editor and you will almost never think about style again. If you use ESLint too, add eslint-config-prettier as the last config so formatting rules in ESLint switch themselves off and the two tools never fight. Biome is an alternative that does both jobs in one fast binary.

The first time you add Prettier to an old project, do it in one separate commit ("format everything") so git blame stays useful, and list that commit in .git-blame-ignore-revs.

Pre-commit hooks (read-only)

Do not trust anyone, including yourself, to remember to run the checks. A pre-commit hook runs them on the staged files only, which keeps it fast.

JSON
{
  "scripts": {
    "lint": "eslint .",
    "format:check": "prettier --check .",
    "typecheck": "tsc --noEmit",
    "test": "vitest run"
  },
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"],
    "*.{json,md,css}": ["prettier --write"]
  }
}

Tools such as husky and lint-staged wire this into git commit. Keep the hook quick (a few seconds); heavy checks like the full test suite belong in CI. The hook is a convenience, and CI is the authority, since a hook can be skipped with --no-verify.

TypeScript strictness (read-only)

If you use TypeScript, make it strict from day one. It is far easier to start strict than to tighten later.

JSON
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "noFallthroughCasesInSwitch": true,
    "forceConsistentCasingInFileNames": true,
    "skipLibCheck": true
  }
}

strict turns on null checks and rejects implicit any. noUncheckedIndexedAccess makes items[0] possibly undefined, which is true and prevents many crashes like the Cannot read properties of undefined error you saw in the debugging lesson. Avoid any and as casts as a habit; each one is a spot where the compiler stopped helping. Prefer unknown for data you have not validated, then narrow it. TypeScript and React covers the React side.

Naming conventions

Names are the most-read part of your code. A few React-wide conventions make a codebase predictable:

  • Components: PascalCase nouns (UserCard, CheckoutForm). Lowercase names are treated as DOM tags.
  • Hooks: camelCase starting with use (useOnlineStatus). The prefix is what lets the linter check the Rules of Hooks.
  • Event handlers: define as handleSubmit, pass as props named onSubmit. The on prefix is the prop (what can happen), handle is the function (what we do about it).
  • Booleans: read like a question: isOpen, hasError, canEdit, shouldRetry.
  • State pairs: [value, setValue], with the setter named after the state.
  • Files: one component per file named like the component (UserCard.jsx), hooks in useThing.js, constants in UPPER_SNAKE_CASE only when they are true constants.
  • Avoid data, info, temp, item2, and abbreviations only you understand. Prefer unreadMessages over list.
Naming rules as a checker

Five names pass and five fail, each failing name followed by the rule it broke. A naming check like this is a good example of a convention a machine can enforce. Whether userCard names a component or a variable is something only ESLint (or TypeScript) can decide in a real project, because it sees how the name is used.

Refactor with a safety net

Clean code is mostly small refactors: extract a component, name a calculation, flatten a nested ternary. The danger is breaking behaviour. Tests are the best safety net (Testing React Components), but even a quick check helps: render the old and new versions with the same props and compare the HTML. renderToStaticMarkup from react-dom/server returns the markup as a string, and it works right here in the browser.

Compare a messy component with its clean refactor

Both inputs produce identical markup, so this refactor changed structure, not behaviour. We gained a stable key (the id instead of the index), named calculations, an early return in place of a nested ternary, === in place of ==, and a CartRow we can reuse. Notice what the check cannot see: keys do not appear in markup, and neither do event handlers or state. Use it for quick comparison of render output, and let real tests cover interactions.

A code review checklist

Reviewers are your last line of defence, and tired reviewers skim. A short written checklist makes reviews faster and fairer. Click through the one below as if reviewing a pull request; the approve button stays disabled until every box is ticked.

A review checklist with progress

The state is a Set of checked indexes, and we copy it before changing it (the rule from the debugging lesson again). Everything else, the count and whether the button is disabled, is derived during render and not stored. That pair of habits is itself two checklist items.

Good review comments name the problem and the reason ("this effect has no cleanup, so each navigation leaves a listener behind"), offer a direction, and separate must-fix from nitpicks (prefix with "nit:"). Let tools catch formatting so humans can talk about design.

Dependency hygiene

Every package you install is code you did not write, will not read, and must keep updated. React projects tend to collect hundreds of transitive dependencies, so build a few habits.

  • Add dependencies deliberately. Ask: how big is it, how maintained is it, can the platform do it already? A date picker is a fair reason; a library to left-pad a string is not. Check the size (for example with a bundle analyzer) before you commit.
  • Commit the lockfile (package-lock.json, pnpm-lock.yaml) so everyone and CI install identical versions, and use npm ci in CI.
  • Update in small, regular steps. Dependabot or Renovate open pull requests for you. Updating monthly is easier than a once-a-year jump across three major versions.
  • Audit. npm audit reports known vulnerabilities. Treat high-severity findings in packages that run in the browser or in your build seriously, and read the report before running blind --force fixes.
  • Remove what you stopped using. Tools like knip or depcheck list unused dependencies and files.
  • One tool per job. Having moment, dayjs and date-fns in one app triples the weight for the same feature.
  • Put build-only tools in devDependencies (ESLint, Vite, testing libraries), so they do not count as runtime code.

Here is the idea of an audit as a runnable sketch. It reads a pretend package.json and a list of imports found in the source, then reports problems a real tool would.

A tiny dependency audit

The audit reports six issues for the pretend project: an any-version range for left-pad and confetti-js, moment and left-pad never imported, ESLint in the wrong section, and two date libraries (moment and dayjs) side by side. Real tools such as npm audit, npm outdated, knip and npm ls do the same job with real data.

Make quality a team habit

  • Automate the boring parts (format, lint, types, tests) and make them required in CI.
  • Agree on conventions once, write them in a short CONTRIBUTING.md, and let the linter enforce what it can.
  • Keep components small. If a component needs a scroll bar to read, split it. If a name needs "and", it does two jobs (Component Design).
  • Delete code. Dead code, old feature flags and commented-out blocks are cost without value. Version control remembers.
  • Refactor continuously in small steps next to feature work, covered by tests, instead of a risky big rewrite.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between Prettier and ESLint?

    A formatter decides how code looks. A linter looks for problems such as hooks in conditions or missing alt text. Use both, and keep their rules from overlapping.
  2. 2. ESLint warns that a useEffect is missing the dependency userId. What is the best response?

    The rule usually points at a real stale-closure bug. Disabling it hides the bug, so only suppress it with a written reason.
  3. 3. Why did our regex-based mini linter flag Comment.jsx although it only mentions dangerouslySetInnerHTML in a comment?

    A real linter parses code into a tree, so it knows a comment from an expression. Text matching creates false positives and misses.
  4. 4. Which naming set follows common React conventions?

    Components are PascalCase, hooks start with use, handler functions are handleX and the props that receive them are onX.
  5. 5. Which habit best reduces risk from third-party packages?

    A lockfile makes installs reproducible, small frequent updates are easier than large ones, and audits plus cleanup keep the dependency list short and safe.

Summary

  • Split the jobs: Prettier formats, ESLint finds likely bugs, TypeScript checks that pieces fit; run all three on save, on commit and in CI.
  • Keep react-hooks/rules-of-hooks as an error and exhaustive-deps on; fix the cause rather than disabling the warning.
  • Write lint rules against the syntax tree, never with regular expressions.
  • Use TypeScript strict, avoid any and unexplained casts.
  • Follow naming conventions: PascalCase components, useX hooks, handleX handlers, onX props, boolean names that read like questions.
  • Refactor in small steps with a safety net (tests, or comparing rendered markup).
  • Review against a short checklist and let tools handle style.
  • Treat dependencies as a liability: add deliberately, commit the lockfile, update often, audit and prune.

Next: TypeScript and React