Is there any way to keep React from re-rendering for each item added to a MobX observed array (using Hooks)

Chance :

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

tudor.gergely :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=368208&siteId=1