Ad

React Js State Variable Updates Automatically Without Setstate Method

- 1 answer

I am working on a react js project. I have a state variable and I initialize that state variable (x_state) with another normal variable (x) during the componentDidMount() method. But whenever my normal variable (x) gets updated it is automatically updating the state variable (x_state).

export class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      x_state: null
    }
    this.x = {}
  }

  componentDidMount() {
    this.setState({
      x_state: this.x
    })
  }
}

The local variable this.x is updating on specific conditions inside the code. whenever the local variable this.x is updating it is automatically updating the state variable x_state. How to prevent the automatic update or automatic setstate method invoking

Ad

Answer

@Maheer Ali & @adiga are correct. Since the state variable x_state and the local variable this.x point to the same object in memory, they both update in conjunction.

You may also use the Spread Operator to copy the properties of the local object to the state variable.

this.setState({
   x_state: { ...this.x }
})
Ad
source: stackoverflow.com
Ad