user2923418 user2923418 - 17 days ago 5
React JSX Question

What is the Mobx way to do handle set state with callbacks

I am trying to convert an existing application that uses set state to use Mobx. How can we i achieve the set state callback functionality using mobx. Do i need to use componentDidUpdate to achieve this functionality?

Answer

setState in React is asynchronous. Modifying an observable in MobX is synchronous, so there is no need for a callback:

@observer
class Example extends Component {
  @observable clicks = 0;

  render() {
    return <button onClick={this.handleClick}> click me </button>;
  }

  handleClick = () => {
    ++this.clicks;
    // The component has now re-rendered!
    ++this.clicks;
    // ...
  };
}