0

I'm still relatively new to React so this may not be an issue or one that's solvable. I put together a very contrived (don't judge :P) experiment using Mobx and React (hooks) here.

What I am wondering is if there is any way to avoid the need to re-render the parent (App) for each item that is added to an array marked observable despite the items being added via concat.

For example:

export class MyModel {
  constructor() {
    this.messages = [];
  }
  addMemo(msg: string, done = false) {
    const memos: Memo[] = [];
    for (let i = 0; i < 10; i++) {
      const memo = new Memo(`${msg}-${i}`);
      memo.letsDance();
      memos.push(memo);
    }
    this.messages = this.messages.concat(memos);
    return memos.shift();
  }
}

decorate(MyModel, {
  messages: observable,
  addMemo: action
});

Causes React to render the consumer 10 times:

const App = () => {
  // ...
  const myModel = useObservable(new MyModel());
  // ...
  return useObserver(() => (
    <div>
      {/* ... */}
    </div>
  ));
};

https://codesandbox.io/s/white-tdd-jh42r

Chance
  • 11,043
  • 8
  • 61
  • 84

1 Answers1

0

Your async letsDance() makes react rerender 10 times (1 for each item which 'dances') check an example here which comments out that part: https://codesandbox.io/s/interesting-mountain-wdtdg

tudor.gergely
  • 4,800
  • 1
  • 16
  • 22