0

I have been playing with mobx computed, but I am having trouble understanding what is happening with the following code:

import React, { Component } from "react";
import { render } from "react-dom";
import { observable, computed } from "mobx";
import { observer } from "mobx-react";

@observer
class Counter extends Component {
  @observable count = 0;
  @observable secondCount = 0;

  @computed
  get countString() {
    console.log("countString Computed");
    return `${this.count} ${this.secondCount}`;
  }

  onChangeCount = () => {
    this.count = this.count + 1;
    this.secondCount = this.secondCount + 1;
  };

  render() {
    console.log("render Counter");
    return (
      <div>
        <p>Count String: {this.countString}</p>
        <button onClick={this.onChangeCount}>Change count</button>
      </div>
    );
  }
}

render(<Counter />, document.getElementById("root"));

When user presses the change count btn, the output is:

countString Computed 
render Counter 
countString Computed 
  • After reading mobx computed fn docs, I understood that if we don't apply @action to the event handlers then the derived fns like computed, autoruns, reactions will be executed once per state mutation. Hence two times computed was called.
  • My question here is, the order in which they are called:

Why is not it like this:

countString Computed 
countString Computed 
render Counter 

or like this:

render Counter 
countString Computed 
countString Computed 

To summarise the question, how the order of execution of logs is being decided in the above snippet?

  • Mobx 5
  • React 0.13.0 is being used
Pavan Gangireddy
  • 417
  • 1
  • 3
  • 13

1 Answers1

0

Refer to the below links

Reaction order

Reaction order in v5

Summary of above links:

You shouldn't rely on execution order of side effects as they are outside of the system.

Chinmaya
  • 11
  • 1