react
react copied to clipboard
[React 19] `eslint-plugin-react-compiler` warning on destructured props mutation
Summary
Trying out eslint-plugin-react-compiler, it warns on the following code:
function Foo({ ...props }) {
props.foo = false;
// Mutating component props or hook arguments is not allowed. Consider using a local variable instead
return <div />;
}
Since props is destructured it's not mutating the original properties, so I believe this is a false positive.
The ESLint rule is designed to prevent mutation of props within a component, which can lead to unpredictable behavior and bugs. Even though destructuring props may create a new object, mutating the destructured props is still considered a bad practice in React.
function Foo({ foo, ...rest }) {
// Create a new object with foo set to false, and spread the rest of the properties into it
const modifiedProps = { foo: false, ...rest };
// Spread the properties of modifiedProps as props to the div element
return <div {...modifiedProps} />;
}
Even though destructuring props may create a new object, mutating the destructured props is still considered a bad practice in React.
Why is it bad practice? I assumed the problem was that a render function shouldn't mutate the props object because react wants to use it still after rendering, e.g. to allow rendering twice with the same properties.
Thanks for filing this. You’re right that technically, destructuring props in this way will create a new object. However, this is only a shallow copy - so it’s okay to set a top-level property, but not for example to mutate the values of the properties.
Our current model for mutability doesn’t support shallow copies, given how error prone they are. So for now we don’t expect to change the implementation here. Basically, it’s technically safe but error prone. We’ll consider if we can specialize the error message in this case.
🤦 Oh ofcourse, it's about tracking mutations. Makes sense, thanks for explaining.