javascriptreactjsfrontendweb-frontendreact-16

Why might componentWillMount be called multiple times with React Fibre?


I've read on multiple sources now that with react Fibre (async rendering) componentWillMount() may be called multiple times.

Why would this happen?


Solution

  • One of the things Fibre is intended to support is high priority vs low priority updates. For example, animations are high priority updates (since jankiness in a 60fps animation is easily noticed), while a change from an api call would be be low priority (who's going to notice a extra hundred milliseconds on something you've got to wait a second for anyway?).

    So a straightforward example with just the standard one call to componentWillMount is as follows: We do a low priority update, and the reconciler begins working its way through the component tree, calling componentWillMount on them, as well as doing its other reconciliation work. Having run short on time, it pauses to let the event loop resume. There's no high priority stuff, so on the next idle callback, it picks up where it left off, finishes the reconciliation and commits the update. There are no extra componentWillMounts.

    Next example: Low priority update starts, and as before the reconciler works through the tree calling componentWillMount on them. As before, it pauses execution, but this time a high priority update comes in. So when reconciliation resumes, react turns its attention to the high priority update. It reconciles that update, and commits it. It's now free to resume the low priority update, but the work it has already done needs to be thrown away, because the high priority update may have made changes that affect what the low priority update will calculate. Since it has to start over, it will need to make those calls to componentWillUpdate again.