javascript / expert
Snippet
Custom Generator-Based Fiber Work Loop Control Flow
This expert React snippet implements a time-sliced work loop using ES6 Generator functions and requestIdleCallback. By yielding control at discrete unit boundaries, it prevents long-running synchronous state calculations from blocking the main thread, mimicking React Fiber work scheduling.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import React, { useEffect, useRef, useState } from 'react';function* createWorkLoop(units) {for (let i = 0; i < units.length; i++) {yield units[i]();}}export function FiberScheduler({ tasks }) {const [completed, setCompleted] = useState([]);const generatorRef = useRef(null);useEffect(() => {generatorRef.current = createWorkLoop(tasks);let frameId;const step = (deadline) => {let work = generatorRef.current?.next();while (work && !work.done && deadline.timeRemaining() > 0) {if (work.value) setCompleted((prev) => [...prev, work.value]);work = generatorRef.current.next();}if (work && !work.done) {frameId = requestIdleCallback(step);}}; globalThis.requestIdleCallback ? (frameId = requestIdleCallback(step)) : step({ timeRemaining: () => 1 });return () => cancelIdleCallback?.(frameId);}, [tasks]);return <div>Completed units: {completed.length}</div>;}
react
Breakdown
1
function* createWorkLoop(units) {
Defines a generator function to step through work items incrementally.
2
let work = generatorRef.current?.next();
Advances the generator by executing a single work unit until deadline expiration.
3
while (work && !work.done && deadline.timeRemaining() > 0) {
Executes tasks continuously only while frame budget permits.