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/immutabilityFull Name in @eslint-react/eslint-plugin
@eslint-react/immutabilityFeatures
๐งช
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
- React Docs:
immutabilityLint Rule - React Docs: Components and Hooks must be pure
- React Docs: Keeping Components Pure
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.