# Pre-commit Hooks & Husky — ESLint and Prettier: Code Quality and Formatting

Source: https://www.skillbyai.com/en/eslint-prettier/eslint-prettier-14

> Block bad commits with Husky and lint-staged so ESLint and Prettier run only on staged files.

## Husky workflow

Husky runs ESLint and Prettier before each commit, blocking bad commits. `lint-staged` runs the tools only on staged files for speed.

## Setting up Husky

Install Husky and configure pre-commit hook to lint before commits.

```bash
npm install --save-dev husky lint-staged
npx husky init           # creates .husky/pre-commit and a prepare script

# .husky/pre-commit
npx lint-staged

# package.json
"lint-staged": {
  "*.{js,ts,tsx}": "eslint --fix",
  "*.{js,ts,tsx,json,md,css}": "prettier --write"
}
```

Output:

```
Husky and lint-staged configured
```

## Skip when necessary

Use `git commit --no-verify` to bypass hooks in emergencies (e.g., hotfix). But document why and fix it immediately after.

Quick check

**Quiz:** What does lint-staged do?

- [ ] Lints all files in the repo.
- [ ] Stages files automatically.
- [ ] Installs Node
- [x] Runs linters only on files staged for commit.

*Answer:* Runs linters only on files staged for commit.. lint-staged improves speed by checking only changed files, not the entire codebase.
