I’m not certain exactly what the linter is tripping on, but generally direct references to state variables are only discouraged if you’re assigning, not if you’re simply referencing to capture a value. So
const something = this.state.something;
should be fine, whereas
this.state.something = something;
would not be. That being said, this would also be ok
const something = this.state.something;
something = somethingElse;
because even though something
came from the state, the assignment here is to the variable, not a property of the state or some state-defined reference.
Using object spread ({...}
) helps protect against this - to a degree - because it copies properties from one object to another. This expression
{ ...this.state }
creates a new object with copies of all the properties in this.state
. This means any assignments to this object would not affect the original state because it would be modifying the object created in that expression instead.
const stateCopy = { ...this.state };
stateCopy.something = somethingElse; // does not affect this.state
However, if you’re using destructuring to capture a single value from this expression like so
const { something } = { ...this.state };
then this is effectively no different than saying
const something = this.state.something;
Both assign the local variable something
to the same value - the value in this.state.something
. The fact that the something
property was copied into an intermediary object with a spread expression in the first variation does not change what that value is or how it behaves as a local variable.
Depending on the value of something
, all of this may be inconsequential. Any primitive value in something
would be considered safe since you wouldn’t be able to assign any property internal to that value. This would not be the case if something
were an object value. If you were able to say
something.anotherProperty = anotherValue;
Then you run the risk of modifying the state without going through setState()
which is a no-no. Object spread does not protect you against this either because it does not do a deep copy. It only copies direct properties of one object to another. It does not copy properties of properties meaning anotherProperty
would be a reference to the same anotherProperty
in this.state
even if object spread was used to create something
as seen in the earlier code sample.