BarakOren
BarakOren

Reputation: 109

how to put this.state into a variable that will not change after the state changes?

simple question(i hope) how can i save this.state into a var, without it will change when the this.state changes? the question will be more clear with the code

this.state={x: "123"}
function change(){
   this.setState({x: "456")}
}

so again, i wanna put the first state into a var, that will NEVER change, even after we use change() any ideas?

Upvotes: 0

Views: 926

Answers (2)

TeaCoder
TeaCoder

Reputation: 1977

You can store the value in an instance level variable in the class constructor.

constructor(props) {
  this.myPermanentState = {x: "123"};
  this.state = {x: "123"};
}

// now calling change will not affect the value of `myPermanentState`
function change(){
   this.setState({x: "456"});
   console.log(this.myPermanentState);
}

If you are using React 16 with hooks, you might be able to use the useRef hook for similar results.

Upvotes: 1

encryptedcurse
encryptedcurse

Reputation: 103

You can create a variable that contains the initial state and assign its value to this.state.

const initialState = {x: "123"};
...
this.state = initialState;

Upvotes: 0

Related Questions