Eslint Enforce Named Function In Useeffect

2 menit baca.

Anonymous functions di useEffect bikin debugging sakit hati. Kalau ada yang error, console kamu muncul:

at Anonymous function (index.js:12345)

Tidak membantu. Ini cara enforce named functions.

Rule ESLint-nya

Pakai react-hooks/rules-of-use — sudah menangkap banyak issue, tapi bisa tambah custom rule untuk named functions.

Opsi 1: Pakai rule dari plugin

Install eslint-plugin-react-hooks:

npm install -D eslint-plugin-react-hooks

Tambahkan di .eslintrc:

{
  "plugins": ["react-hooks"],
  "rules": {
    "react-hooks/rules-of-use": "error",
    "react-hooks/exhaustive-deps": "warn"
  }
}

Opsi 2: Tulis custom rule

Kalau mau strict named function enforcement, tambahkan ini di ESLint config:

rules: {
  'no-new-func': 'error',
  'prefer-arrow-callback': 'error'
}

Tapi ini terlalu luas — memaksa arrow functions di mana-mana.

Opsi 3: Gunakan pola yang benar

Pendekatan terbaik bukan rule — tapi code review discipline. Tulis effects seperti ini:

// Buruk — anonymous function
useEffect(() => {
  fetchData();
}, []);

// Bagus — named function
useEffect(function fetchDataOnMount() {
  fetchData();
}, []);

Atau extract ke function di luar:

function fetchData() {
  // ...
}

useEffect(() => {
  fetchData();
}, []);

Kenapa penting

  • Named functions muncul di stack traces
  • Lebih mudah identifikasi effect mana yang cause masalah
  • Kode jadi self-documenting

Selesai. Tidak perlu ESLint config yang kompleks — cukup tulis (atau review) dengan intent.

Latest Posts