[javascript] Where to declare variable in react js

I am trying to declare a variable in a react-js class. The variable should be accessible in different functions. This is my code

class MyContainer extends Component {
    constructor(props) {
        super(props);
        this.testVariable= "this is a test";  // I declare the variable here
    }
    onMove() {
        console.log(this.testVariable); //I try to access it here
    }
}

On onMove, the value of this.testVariable is undefined. I Know that I could put the value on the state but I don't want to do it because each time the value changes, render() will be called which is not necessary. I am new to react, did I make something wrong?

This question is related to javascript reactjs

The answer is


Assuming that onMove is an event handler, it is likely that its context is something other than the instance of MyContainer, i.e. this points to something different.

You can manually bind the context of the function during the construction of the instance via Function.bind:

class MyContainer extends Component {
  constructor(props) {
    super(props);

    this.onMove = this.onMove.bind(this);

    this.test = "this is a test";
  }

  onMove() {
    console.log(this.test);
  }
}

Also, test !== testVariable.