logoESLint React

immutability

Validates against passing functions that mutate captured local variables into frozen contexts such as JSX props, hook arguments, and hook return values.

This is an evaluation implementation and may contain false positives or negatives that have not yet been fully audited. Review each report carefully before applying fixes.

Full Name in eslint-plugin-react-x

react-x/immutability

Full Name in @eslint-react/eslint-plugin

@eslint-react/immutability

Features

๐Ÿงช

Rule Details

A function that mutates a variable captured from an enclosing scope is, in effect, a mutable value: unlike a mutable array or object, the caller of the function has no way to prevent the mutation from happening once the function is invoked. This rule flags such functions when they are handed to a context that expects a stable, "frozen" value:

  • Passed as a JSX prop
  • Passed as an argument to a hook call
  • Returned from a custom hook

Mutations to ref-like values (an identifier named ref or ending in Ref) are exempted, since refs are mutable by design.

Examples

// ๐Ÿ”ด Problem: `fn` mutates `cache` after render
function Component() {
  const cache = new Map();
  const fn = () => {
    cache.set("key", "value");
  };
  return <Foo fn={fn} />;
}
// ๐ŸŸข Recommended: use state instead of a captured mutable variable
function Component() {
  const [cache, setCache] = useState(() => new Map());
  const fn = () => {
    setCache((prev) => new Map(prev).set("key", "value"));
  };
  return <Foo fn={fn} />;
}

Versions

Resources

Further Reading


See Also

  • react-x/purity
    Validates against passing functions that mutate captured local variables into frozen contexts such as JSX props, hook arguments, and hook return values.

On this page