CodeQL documentation

Direct state mutation

ID: js/react/direct-state-mutation Kind: problem Security severity: Severity: warning Precision: very-high Tags: - quality - reliability - correctness - frameworks/react Query suites: - javascript-code-quality.qls - javascript-security-and-quality.qls 

Click to see the query in the CodeQL repository

React components have a state property. This property contains data associated with the component that may change over time. Although properties of the state object can be read freely, they should not be updated directly, since such modifications could be overwritten by asynchronous updates performed by setState.

Recommendation

Rewrite the code to use setState instead.

Example

The following example component uses setInterval to register method tick as a callback that is invoked every second and updates state.now directly:

class Clock extends React.Component {  componentDidMount() {  setInterval(() => this.tick(), 1000);  }  tick() {  this.state.now = Date.now();  } } 

Instead, setState should be used:

class Clock extends React.Component {  componentDidMount() {  setInterval(() => this.tick(), 1000);  }  tick() {  this.setState({ now: Date.now() });  } } 

References