14

I have a variable that I'm creating in componentDidMount() and I'd like it to be available in componentDidUpdate(). Any thoughts? Code looks like this:

class Example extends Component {
  componentDidMount() {
    const myVariable = 'this thing';
  }

  componentDidUpdate() {
    // I'd like my variable to be accessible here
    console.log(myVariable);
  }

  render() {...}
}
jasonetco
  • 336
  • 1
  • 3
  • 11

1 Answers1

33

Save it to the component then.

componentDidMount() {
    this.myVariable = 'this thing';
}

componentDidUpdate() {
    // I'd like my variable to be accessible here
    console.log(this.myVariable);
}

Also, as @Gosha Arinich helpfully pointed it out - be aware that if you do plan to re-use this variable throughout the component's lifecycle and update it and/or render it - it is best placed into the state of the component (this.state).

Elod Szopos
  • 3,168
  • 17
  • 31
  • 4
    Oh my god I had no idea you could do that... That's excellent! Thank you! – jasonetco Jun 27 '16 at 16:48
  • 2
    @jasonetco Happy to help. Make sure you read up on the usage of `this`. It is one of the harder go grasp concepts in Javascript. A good relevant question and multiple answers can be found [here](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Elod Szopos Jun 27 '16 at 16:53
  • 1
    Also keep in mind that if this value is going to be updated during component lifecycle, and if it's used in `render`, it's better to put it into state. – Gosha Arinich Jun 27 '16 at 17:35
  • @GoshaArinich I get that, but in this case I don't need to be updating it, only using the value. Besides which, as far as I understand it's a bad idea to use `setState()` in `componentDidMount()` – jasonetco Jun 27 '16 at 18:21