I got nerd sniped into React's source code to understand how the scheduler works... 😅
🖊️ The typing part
When you type in a search box with useDeferredValue, React handles it in two parts.
First, the actual typing needs to feel snappy, so React gives it high priority (UserBlockingPriority) and makes sure it completes quickly (within 250ms).
This is why your typed characters appear instantly in the input.
🖊️ The deferred part
Updating the search results gets lower priority (NormalPriority) and can take longer to complete (up to 5 seconds). SlowList will only update once the deferred value has updated.
🖊️ React breaks it work into chunks
React breaks this work into small 5ms chunks. After each chunk, it lets the browser catch its breath and handle any important stuff like responding to more typing or running animations.
If React didn't do this, the browser would remain unresponsive while it does its job.
🖊️ React uses a priority queue
To keep track of all this work, React uses a priority queue (implemented as a min heap) to make sure the most important tasks get done first.
And to prevent things from taking forever (e.g. useDeferredValue waiting forever to update), it sets timeouts. It's like a deadline system.
If a task hits its deadline, React says "okay, time's up" and just gets it done.
🖊️ Summary
The system is beautiful. It's a priority based system where each task has a deadline so the user doesn't need to wait forever.
I'm thinking of starting a series where we dig into React's source code and demystify each package.
ReactFiber is another fun one and how they use double buffering. I ended up reading some of the source code there too.
React performance trick: use `useDeferredValue` to update values without blocking user interactions