Upgrade to Pro — share decks privately, control downloads, hide ads and more …

๐Ÿ‡จ๐Ÿ‡ฟ PragueJS 2023 #4

๐Ÿ‡จ๐Ÿ‡ฟ PragueJS 2023ย #4

โ„น๏ธ Deep diving on Concurrent React

Writing fluid user interfaces becomes more and more challenging as the application complexity increases. In this talk, weโ€™ll explore how proper scheduling improves your appโ€™s experience by diving into some concurrent React features, understanding their rationales, and how they work under the hood.

Matheus Albuquerque

April 27, 2023
Tweet

More Decks by Matheus Albuquerque

Other Decks in Programming

Transcript

  1. DEEP DIVING ON CONCURRENT REACT โ†‘ ALL THE LINKS! ๐Ÿค“

    ๐Ÿง‘๐Ÿซ @techlabs ๐Ÿฆ @ythecombinator ๐Ÿ‘จ๐Ÿ’ป @medallia โšก Perf GDE
  2. DEEP DIVING ON CONCURRENT REACT โ†‘ ALL THE LINKS! ๐Ÿค“

    ๐Ÿบ LETโ€™S DISCUSS MORE AFTER!
  3. #QUESTION ๐Ÿค” If you were to summarize Concurrent React in

    one word/expression, whatโ€™d be your pick?
  4. #QUESTION ๐Ÿค” If you were to summarize Concurrent React in

    one word/expression, whatโ€™d be your pick? e.g. fibers = units of work Concurrent React = ???
  5. DEEP DIVING ON CONCURRENT REACT If you were to summarize

    Concurrent React in one word/expression, whatโ€™d be your pick?
  6. TASKS JAVASCRIPT STYLES LAYOUT PAINT COMPOSITE A UNIT OF WORK

    THAT THE BROWSER DOES TO RENDER A FRAME
  7. LONG TASKS โ† IF A TASK TAKES MORE THAN 50

    MS, USER INPUT FEELS DELAYED โ† BASED ON THE USER-CENTRIC PERFORMANCE MODEL CALLED RAIL โ† THEY TAKE TOO LONG AND BLOCK OTHER TASKS
  8. #RESEARCH ๐Ÿ“š Phone users experience slow First Input Delay on

    7x more websites. โ€”โ€‰Web Almanac By HTTP Archive, 2021
  9. RESEARCH RESULTS: โ† LONG TASKS DELAYED TTI โ† MOBILE HAD

    UP TO หœ12X LONGER LONG TASKS โ† OLDER DEVICES COULD BE SPENDING HALF OF THEIR LOAD-TIME ON LONG TASKS โ€”โ€‰AKAMAI AND CHROME RESEARCH, 2017 LONG TASKS
  10. WORKERS โ† DATA EXCHANGE IS THROUGH MESSAGE-PASSING โ† NO ACCESS

    TO ANY VARIABLES/CODE FROM THE PAGE THAT CREATED THEM OR VICE VERSA โ† NO ACCESS TO THE DOM, MAKING UI UPDATES FROM A WORKER BARELY IMPOSSIBLE โ† TWO MODELS: ACTORS & SHARED MEMORY ๐Ÿคฟ
  11. ACTORS โ† EACH ACTOR MAY OR MAY NOT RUN ON

    A SEPARATE THREAD โ† EACH ACTOR FULLY OWNS THE DATA IT IS OPERATING ON โ† ACTORS CAN ONLY SEND/REACT TO MESSAGES โ† MAIN THREAD = ACTOR THAT OWNS THE DOM/UI ๐Ÿคฟ
  12. ACTORS โ† EVERY MESSAGE WE SEND NEEDS TO BE COPIED

    โ† BALANCE: MOVING CODE TO A WORKER VS COMMUNICATION OVERHEAD/WORKER BEING BUSY โ† postMessage IS A FIRE-AND-FORGET MESSAGING MECHANISM WITH NO BUILT-IN UNDERSTANDING OF REQUEST AND RESPONSE ๐Ÿคฟ
  13. SHARED MEMORY โ† ONE DEDICATED TYPE: SharedArrayBuffer โ† A LINEAR

    CHUNK OF MEMORY THAT CAN BE MANIPULATED USING TypedArrays OR DataViews โ† IF SENT VIA postMessage, THE OTHER END GETS A HANDLE TO THE EXACT SAME MEMORY CHUNK ๐Ÿคฟ
  14. SHARED MEMORY โ† MOST OF THE APIS ARE BUILT NO

    CONCURRENT ACCESS TO OBJECTS IN MIND โ† YOU BUILD YOUR OWN MUTEXES AND OTHER CONCURRENT DATA STRUCTURES โ† NO DIRECT WAY OF WORKING ON FAMILIAR OBJECTS/ARRAYS; JUST A SERIES OF BYTES ๐Ÿคฟ
  15. WEB ASSEMBLY โ† WORKERS + SharedArrayBuffers TO SUPPORT THE THREADING

    MODEL OF C++ AND OTHERS โ† BEST EXPERIENCE FOR SHARED-MEMORY MODEL โ† FASTER THAN JS WHEN YOU STAY WITHIN WASM, BUT THE MORE YOU HAVE TO CROSS OVER TO JS APIS THE SLOWER IT IS
  16. WEB ASSEMBLY โ† JAVASCRIPT IS OFTEN FASTER AT DOING DOM

    RENDERING โ† HIGH-LEVEL LIBRARIES CAN BE MORE PERFORMANT THAN LOW-LEVEL WASM IMPLEMENTATIONS โ† DOESNโ€™T OFFER LOT OF THE BENEFITS (AND COMFORT) OF JAVASCRIPT
  17. WORKERS โ† GOOD FOR DATA PROCESSING AND CRUNCHING NUMBERS โ†

    HARD TO USE FOR UI-RELATED STUFF โ† HARDER THAN ADJUSTING WORK FOR A SCHEDULER
  18. #QUESTION ๐Ÿค” If you were to summarize Concurrent React in

    one word/expression, whatโ€™d be your pick?
  19. HEURISTICS COOPERATIVE MULTITASKING WITH A SINGLE INTERRUPTIBLE RENDERING THREAD PRIORITY

    LEVELS REGISTER CALLBACKS WITH DIFFERENT PRIORITY LEVELS IN THE BROWSER RENDER LANES ABSTRACTIONS AROUND A BITMASK; BRING GRANULARITY, AVOID OVERHEAD & ALLOW BATCHING SCHEDULING IN REACT
  20. function resourcefulOperation(value: number) { let newValue = String(value); for (let

    i = 0; i < 1000000; i++) { newValue = `${value} + ${i} = ${value + i}`; } return newValue; } function ResourcefulComponent(props: { value: number }) { const { value } = props; const result = resourcefulOperation(value); return <p>{result}</p>; }
  21. function resourcefulOperation(value: number) { let newValue = String(value); for (let

    i = 0; i < 1000000; i++) { newValue = `${value} + ${i} = ${value + i}`; } return newValue; } function ResourcefulComponent(props: { value: number }) { const { value } = props; const result = resourcefulOperation(value); return <p>{result}</p>; }
  22. function* resourcefulOperation(value: number) { let newValue = String(value); while (true)

    { yield; for (let i = 0; i < 1000000; i++) { newValue = `${value} + ${i} = ${value + i}`; } return newValue; } } const initialValue = 0; const scheduler = new Scheduler(resourcefulOperation, initialValue); function ResourcefulComponent(props: { value: number }) { const { value } = props; const result = scheduler.performUnitOfWork(value); return <p>{result}</p>; }
  23. function* resourcefulOperation(value: number) { let newValue = String(value); while (true)

    { yield; for (let i = 0; i < 1000000; i++) { newValue = `${value} + ${i} = ${value + i}`; } return newValue; } } const initialValue = 0; const scheduler = new Scheduler(resourcefulOperation, initialValue); function ResourcefulComponent(props: { value: number }) { const { value } = props; const result = scheduler.performUnitOfWork(value); return <p>{result}</p>; } PROMOTED TO A GENERATOR YIELDING EXECUTION DOING CONCURRENT TASKS
  24. enum SchedulerState { IDLE = "IDLE", PENDING = "PENDING", DONE

    = "DONE", } class Scheduler<T> { state: SchedulerState; result: T; worker: (data: T) = > Generator; iterator: Generator; constructor(worker: (data: T) = > Generator, initialResult: T) { this.state = SchedulerState.IDLE; this.worker = worker; this.result = initialResult; } performUnitOfWork(data: T) { switch (this.state) { case "IDLE": this.state = SchedulerState.PENDING; this.iterator = this.worker(data); throw Promise.resolve(); case "PENDING": const { value, done } = this.iterator.next(); if (done) { this.result = value; this.state = SchedulerState.DONE; return value; } throw Promise.resolve(); case "DONE": this.state = SchedulerState.IDLE; return this.result; } } }
  25. performUnitOfWork(data: T) { switch (this.state) { case "IDLE": this.state =

    SchedulerState.PENDING; this.iterator = this.worker(data); throw Promise.resolve(); case "PENDING": const { value, done } = this.iterator.next(); if (done) { this.result = value; this.state = SchedulerState.DONE; return value; } throw Promise.resolve(); case "DONE": this.state = SchedulerState.IDLE; return this.result; } }
  26. function resourcefulOperation(value: number) { let newValue = String(value); for (let

    i = 0; i < 1000000; i++) { newValue = `${value} + ${i} = ${value + i}`; } return newValue; } function ResourcefulComponent(props: { value: number }) { const { value } = props; const result = resourcefulOperation(value); return <p>{result}</p>; }
  27. function resourcefulOperation(value: number) { let newValue = String(value); for (let

    i = 0; i < 1000000; i++) { newValue = `${value} + ${i} = ${value + i}`; } return newValue; } function ResourcefulComponent(props: { value: number }) { const [_, startTransition] = useTransition(); const [result, setResult] = useState(""); useEffect(() = > { startTransition(() = > { const newResult = resourcefulOperation(props.value); setResult(newResult); }); }, [props.value]); return <p>{result}</p>; }
  28. โ† A COOPERATIVE MULTITASKING MODEL โ† A SINGLE INTERRUPTIBLE RENDERING

    THREAD โ† RENDERING CAN BE INTERLEAVED WITH OTHER MAIN THREAD TASKS (AND OTHER REACT RENDERS) โ† AN UPDATE CAN HAPPEN IN THE BACKGROUND WITHOUT BLOCKING THE RESPONSE TO NEW INPUT SCHEDULING IN REACT
  29. โ†“ ORIGINAL RENDER TASK USER INPUT โ†’ โ†‘ HIGHER PRIORITY

    RENDER TASK โ†“ RESUME ORIGINAL RENDER TASK
  30. โ† IT YIELDS EXECUTION IS BACK TO THE MAIN THREAD

    EVERY 5MS โ† IT'S SMALLER THAN A SINGLE FRAME EVEN ON 120FPS, SO IT WON'T BLOCK ANIMATIONS โ† IN PRACTICE, RENDERING IS INTERRUPTIBLE HEURISTICS
  31. PRIORITY TIMEOUT WHEN I m m ediate SYNCHRONOUSLY TASKS THAT

    NEED TO RUN SYNCHRONOUSLY UserBlocking 250MS RESULTS OF A USER INTERACTION (E.G. A BUTTON CLICK) Normal 5S UPDATES THAT DONโ€™T HAVE TO FEEL INSTANTANEOUS Low 10S TASKS THAT CAN BE DEFERRED BUT MUST STILL COMPLETE EVENTUALLY (E.G. AN ANALYTICS NOTIFICATION) Idle NO TIMEOUT TASKS THAT DO NOT HAVE TO RUN AT ALL (E.G. HIDDEN OFFSCREEN CONTENT)
  32. โ† ONE LANE = ONE BIT IN A BITMASK โ†

    ONE UPDATE IN REACT = ONE LANE โ† UPDATES IN THE SAME LANE RENDER IN THE SAME BATCH. DIFFERENT LANES, SEPARATE BATCHES. โ† 31 LEVELS OF GRANULARITY (= ONE BITMASK) RENDER LANES ๐Ÿคฟ
  33. โ† ALLOWS TO CHOOSE WHETHER TO RENDER MULTIPLE TRANSITIONS IN

    A SINGLE BATCH OR RENDER THEM INDEPENDENTLY โ† REDUCES OVERHEAD OF MULTIPLE LAYOUT PASSES, STYLE RECALCULATIONS, AND MULTIPLE PAINTS RENDER LANES ๐Ÿคฟ
  34. SCHEDULING IN REACT HANDLING LOTS OF DATA WITH THE useTransition

    HOOK TACKLING WASTED RENDERS WITH THE useSyncExternalStore HOOK HYDRATION IMPROVEMENTS WITH SELECTIVE HYDRATION & CONCURRENT REACT PROFILER ENHANCEMENTS INSPECT TRANSITIONS, GET WARNS, AND MUCH MORE!
  35. ๐Ÿ˜” NON-PRACTICALโ€ฆ โ† FINDING PRIMES โ† CRACKING PASSWORDS โ† SIERPINSKI

    TRIANGLE ๐Ÿ˜Š PRACTICALโ€ฆ โ† RENDERING MANY DATA-POINTS โ† RENDERING ON A <canvas> โ† PROCESSING DATA
  36. DAILY VISITORS (BEFORE) const DailyVisitors = () = > {

    const [data, setData] = useState(initialData); useEffect(() = > { setData(initialData); }, []); const onChange = (newData) = > { setData(newData); }; return ( <Dashboard data={data} initialData={initialData} onChange={onChange} /> ); }; export default DailyVisitors;
  37. DAILY VISITORS (AFTER) const DailyVisitors = () = > {

    const [data, setData] = useState(initialData); const [, startTransition] = useTransition(); useEffect(() = > { setData(initialData); }, []); const onChange = (newData) = > { startTransition(() = > { setData(newData); }); }; return ( <Dashboard data={data} initialData={initialData} onChange={onChange} /> ); }; export default DailyVisitors;
  38. โ† หœ100K + POINTS PLOTTED โ† SUPPORT FOR SEARCHING AND

    FILTERING โ† USED WORKERS + REDUX-SAGA UTILITIES + DEBOUNCING โ† COULD'VE USED TRANSITIONS CASE #1: MAPS
  39. CASE #2: GAME ADMIN โ† THOUSANDS OF REAL-TIME PLAYERS MESSAGING

    โ† SUPPORT FOR SEARCHING AND FILTERING โ† USED VIRTUALIZATION AND MEMOIZATION โ† COULD'VE USED TRANSITIONS
  40. useSyncExternalStore() function useSyncExternalStore<Snapshot>( subscribe: (onStoreChange: () = > void) =

    > () = > void, getSnapshot: () = > Snapshot, getServerSnapshot?: () = > Snapshot ): Snapshot;
  41. useLocation() function Pathname() { const { pathname } = useLocation();

    return <Badge title={pathname} subtitle="pathname" />; } function Hash() { const { hash } = useLocation(); return <Badge title={hash} subtitle="hash" />; }
  42. useLocation() function Pathname() { const { pathname } = useLocation();

    return <Badge title={pathname} subtitle="pathname" />; } function Hash() { const { hash } = useLocation(); return <Badge title={hash} subtitle="hash" />; } OVER-RETURNING HOOK
  43. useLocation() function Pathname() { const { pathname } = useLocation();

    return <Badge title={pathname} subtitle="pathname" />; } function Hash() { const { hash } = useLocation(); return <Badge title={hash} subtitle="hash" />; }
  44. useLocation() useHistorySelector() function useHistorySelector(selector) { const history = useHistory(); return

    useSyncExternalStore(history.listen, () = > selector(history)); } function Pathname() { const pathname = useHistorySelector((history) = > history.location.pathname); return <Badge title={pathname} subtitle="pathname" />; } function Hash() { const hash = useHistorySelector((history) = > history.location.hash); return <Badge title={hash} subtitle="hash" />; }
  45. function useHistorySelector(selector) { const history = useHistory(); return useSyncExternalStore(history.listen, ()

    = > selector(history)); } function Pathname() { const pathname = useHistorySelector((history) = > history.location.pathname); return <Badge title={pathname} subtitle="pathname" />; } function Hash() { const hash = useHistorySelector((history) = > history.location.hash); return <Badge title={hash} subtitle="hash" />; } useLocation() useHistorySelector()
  46. โ† BEFORE, HYDRATION COULD ONLY BEGIN AFTER THE ENTIRE DATA

    WAS FETCHED AND RENDERED โ† USERS COULDNโ€™T INTERACT WITH THE PAGE UNTIL HYDRATION WAS COMPLETE FOR THE WHOLE PAGE โ† PARTS OF YOUR APP THAT LOAD FAST WOULD ALWAYS HAVE TO WAIT FOR THE SLOW ONES HYDRATION
  47. โ† REACT WON'T WAIT FOR A COMPONENT TO LOAD TO

    CONTINUE STREAMING THE REST OF THE HTML โ† REACT PRIORITIZES HYDRATING THE PARTS THAT THE USER INTERACTED WITH BEFORE THE REST SELECTIVE HYDRATION
  48. โ† COMPONENTS CAN BECOME INTERACTIVE FASTER BY ALLOWING THE BROWSER

    TO DO OTHER WORK AT THE SAME TIME AS HYDRATION โ† RESULTS IN LOWER FIRST INPUT DELAY (FID) AND INTERACTION TO NEXT PAINT (INP) SELECTIVE HYDRATION
  49. โ† I/O LIBRARIES LIKE react-fetch โ† BUILT-IN <Cache> FOR DATA

    FETCHING LIBRARIES TO INTEGRATE WITH <Suspense> โ† <Suspense> FOR CPU-BOUND TREES TO IMMEDIATELY FALLBACK WITHOUT EVEN TRYING TO RENDER THE FUTURE ๐Ÿคฟ
  50. โ† useInsertionEffect FOR STYLESHEET LIBRARIES โ† THE <Offscreen> COMPONENT โ†

    SERVER COMPONENTS โ† NATIVE SCHEDULING PRIMITIVES ON THE BROWSER THE FUTURE ๐Ÿคฟ
  51. SCHEDULING API โ† A MORE ROBUST SOLUTION FOR SCHEDULING TASKS

    โ† CONTROL AND SCHEDULE PRIORITIZED TASKS IN A UNITED AND FLEXIBLE WAY โ† INTEGRATED DIRECTLY INTO THE EVENT LOOP โ† ALIGNED WITH THE WORK OF THE REACT TEAM AND IN COOPERATION WITH GOOGLE, W3C AND OTHERS
  52. scheduler.postTask() SCHEDULE AND CONTROL PRIORITIZING TASKS. scheduler.wait() YIELD AND RESUME

    AFTER SOME AMOUNT OF TIME OR PERHAPS AFTER AN EVENT HAS OCCURRED. scheduler.yield() BREAK UP LONG TASKS BY YIELDING TO THE BROWSER AND CONTINUING AFTER BEING RESCHEDULED. isInputPending() DETERMINE IF THE CURRENT TASK IS BLOCKING INPUT EVENTS. SCHEDULING API
  53. scheduler.postTask() scheduler.postTask(() = > { console.log('React Brussels'); }, { delay:

    10 }); scheduler.postTask(() = > { console.log('React India'); }); scheduler.postTask(() = > { console.log('React Alicante'); }); / / 'React India' 'React Alicante' 'React Brussels'
  54. scheduler.postTask() const controller = new TaskController({ priority: "user-blocking" }); const

    signal = controller.signal; console.log(signal.priority); / / 'user-blocking' console.log(signal.aborted); / / 'false' scheduler.postTask(doWork, { signal }); controller.setPriority("background"); controller.abort();
  55. isInputPending() while (workQueue.length > 0) { if (navigator.scheduling.isInputPending()) { /

    / Stop doing work to handle any input event break; } let job = workQueue.shift(); job.execute(); }
  56. #1 DEEP DIVING ON CONCURRENT REACT REACT IS NOT REACTIVE,

    BUT IT IS CONCURRENT AND THAT MIGHT BE ENOUGH FOR YOU
  57. #2 DEEP DIVING ON CONCURRENT REACT REACT HAS BEEN PUSHING

    WEB APIS TO THE FUTURE E.G. THE SCHEDULER API AND DISCUSSIONS AROUND EFFECT HANDLERS
  58. #3 DEEP DIVING ON CONCURRENT REACT REACT TRIES TO ADDRESS

    THE LACK OF SOME JS/WEB PLATFORM RESOURCES E.G. EFFECT HANDLERS, CONTINUATIONS & THE SCHEDULER API
  59. export const Hello = () = > { const value

    = usePromise(() = > delay("Hello, React Advanced! ๐Ÿ‘‹ ๐Ÿ‡ฌ๐Ÿ‡ง ", 5000)); return <Typography variant="h3">{value}</Typography>; }; function Demo() { return ( <Grid container justifyContent="center"> <Suspense fallback={<Loading message="Loading . . . " />}> <Hello /> </Suspense> </Grid> ); } ๐Ÿคฟ
  60. #4 DEEP DIVING ON CONCURRENT REACT UNDERSTANDING THESE INTERNALS AND

    THEIR RATIONALES HELPS US IMPLEMENT OUR OWN ABSTRACTIONS E.G. THE GENERATOR-BASED SCHEDULER & FIRST CLASS SUPPORT FOR PROMISES
  61. DEEP DIVING ON CONCURRENT REACT THATโ€™S ALL, FOLKS! THANKS! ๐Ÿค

    QUESTIONS? MATHEUS ALBUQUERQUE โ†‘ ALL THE LINKS! ๐Ÿค“