Enforce Named Functions in useEffect with ESLint

Published on · Updated on
2 min read.
Tags: JavaScriptESLintReact

Arrow functions in useEffect have no name, so a stack trace through an effect shows up as:

at Anonymous function (index.js:12345)

That doesn't tell you which effect broke. Name the function, and ESLint can enforce it.

Quick answer

eslint-plugin-react-hooks has no rule for this. Its rules are rules-of-hooks and exhaustive-deps, plus the React Compiler rules in v6 and later. Use two core ESLint rules instead: no-restricted-syntax to ban an arrow function as the effect callback, and func-names to ban unnamed function expressions.

In eslint.config.js (flat config, tested on ESLint 9.39):

export default [
  {
    files: ["**/*.{js,jsx,ts,tsx}"],
    rules: {
      "func-names": ["error", "always"],
      "no-restricted-syntax": [
        "error",
        {
          selector:
            "CallExpression[callee.name=/^use(Layout)?Effect$/] > ArrowFunctionExpression:first-child",
          message: "Name your effect: useEffect(function doThing() { ... }, [])",
        },
      ],
    },
  },
];

The selector matches an arrow function as the first argument of useEffect or useLayoutEffect. It doesn't catch React.useEffect(...), because the callee there is a member expression.

func-names applies to every function expression in your code, not only effects, so a callback like items.map(function (item) { ... }) needs a name too. Arrow functions outside effects aren't affected.

What passes and what fails

// Error: arrow function
useEffect(() => {
  fetchData();
}, []);

// Error: unnamed function expression
useEffect(function () {
  fetchData();
}, []);

// OK: named function expression
useEffect(function fetchDataOnMount() {
  fetchData();
}, []);

// OK: pass a named function
useEffect(fetchData, []);

With this config, the first two cases error and the last two pass. With a named function, the stack trace reads at fetchDataOnMount instead of at Anonymous function.

Extracting the effect

For longer effects, move the body into a named function and pass it directly:

function syncTitle() {
  document.title = "Dashboard";
}

useEffect(syncTitle, []);

This only works when the effect doesn't use props or state. If it does, define the function inside the component and pass it by name, or keep the named function expression inline.