Fiber's Secret Sauce

How React Cooperates Scheduling With The Browser

A React Fiber Is a Unit of Work

  • Can have a priority
  • Can be tracked, scheduled, paused, and aborted
  • Every React element has a Fiber Node to represent its pending & completed work

But The Browser Has Work to Do Too!

  • Event handlers
  • Updates to the Browser UI
  • Layout recalculations
  • etc...
  • etc...

How can React know when it's a good time to "get to work"?

RequestIdleCallback

RequestIdleCallback

  • Browser can tell us when it's no longer busy
  • Can also tell us how much time we have before it gets busy again
  • This is cool because we can cooperate and prioritize work with the help of the browser.
requestIdleCallback(myNonEssentialWork);


function myNonEssentialWork (deadline) {
  while (deadline.timeRemaining() > 0 && tasks.length > 0)
    doWorkIfNeeded();

  if (tasks.length > 0)
    requestIdleCallback(myNonEssentialWork);
}
var eventsToSend = [];

function onNavClick () {
  eventsToSend.push(
    {
      category: 'button',
      action: 'click',
      label: 'nav',
      value: 'open'
    });

  schedulePendingEvents();
}

function schedulePendingEvents() {
  requestIdleCallback(
    processPendingAnalyticsEvents, 
    { timeout: 2000 }
  );
}

Example: Sending Analytic Events

function processPendingAnalyticsEvents (deadline) {
  while (deadline.timeRemaining() > 0 && eventsToSend.length > 0) {
    var evt = eventsToSend.pop();

    ga('send', 'event',
        evt.category,
        evt.action,
        evt.label,
        evt.value);
  }

  if (eventsToSend.length > 0)
    schedulePendingEvents();
}

Fin

  • Fire our analytics events in the background and avoid potentially blocking the main thread.
  • Only do the work of sending the events during the browser's idle time
  • And reschedule the remaining events to be sent during the next "idle" time.

RequestIdleCallback allowed us to ....

React uses this flow (almost exactly) to schedule units of work. Neat.

Thanks Y'allĀ 

Made with Slides.com