React scheduler's `unstable_runWithPriority` doesn't use `priority` in any way

7.2k views Asked by At

I ran a profiler on the following code:

function App() {
  const [ counter, setCounter ] = useState(0);
  return <div>
    <div>{counter}</div>
    <button onClick={(e) => setCounter(counter + 1)}>Inc</button>
  </div>
}

enter image description here Which is pretty standard, what's interesting is the unstable_runWithPriority function. It takes priority as a parameter but doesn't schedule anything, instead it calls the event handler.

Regardless of what the priority is, it just runs it all the same. Can someone elaborate the necessity of this function?

Shouldn't there be some sort of task or a microtask scheduled based on priority?

2

There are 2 answers

1
Burak Can On

It sets currentPriorityLevel (a global variable which is used by other functions in the chain) to given priority. Runs the task and returns currentPriorityLevel back to its original value.

0
gwl002 On

Let's use your demo to illustrate.

  1. onClick => currentPriorityLevel = UserBlockingPriority
  2. setCounter(eventHandler in runWithPriority) => createUpdate(eventTime, lane, suspenseConfig)
  3. the lane comes from requestUpdateLane(fiber, suspenseConfig)
  4. so the lane is come from the currentPriorityLevel;
    function requestUpdateLane(
      fiber: Fiber,
      suspenseConfig: SuspenseConfig | null,
    ): Lane {
      const schedulerPriority = getCurrentPriorityLevel();
      let lane;
      if (
        (executionContext & DiscreteEventContext) !== NoContext &&
        schedulerPriority === UserBlockingSchedulerPriority
      ) {
        lane = findUpdateLane(InputDiscreteLanePriority, currentEventWipLanes);
      } else {
        const schedulerLanePriority = schedulerPriorityToLanePriority(
          schedulerPriority,
        );
        lane = findUpdateLane(schedulerLanePriority, currentEventWipLanes);
      }
      return lane;
    }