$30 off During Our Annual Pro Sale. View details »

๐Ÿ‡ง๐Ÿ‡ช React Brussels 2022

๐Ÿ‡ง๐Ÿ‡ช React Brusselsย 2022

โ„น๏ธ Deep diving on Concurrent React

Writing fluid user interfaces become 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

October 14, 2022
Tweet

More Decks by Matheus Albuquerque

Other Decks in Programming

Transcript

  1. Salut, React Brussels! ๐Ÿ‘‹ ๐Ÿ‡ง๐Ÿ‡ช DEEP DIVING ON CONCURRENT REACT

    โ€ข THE 14TH OF OCTOBER, 2022.
  2. DEEP DIVING ON CONCURRENT REACT MATHEUS ALBUQUERQUE

  3. DEEP DIVING ON CONCURRENT REACT ๐Ÿง‘๐Ÿซ @techlabs ๐Ÿฆ @ythecombinator ๐Ÿ‘จ๐Ÿ’ป

    @medallia โ†‘ ALL THE LINKS! ๐Ÿค“ ๐Ÿ‡ง๐Ÿ‡ท Matheus Albuquerque
  4. DEEP DIVING ON CONCURRENT REACT ๐Ÿบ DEEP DIVE! LETโ€™S DISCUSS

    MORE IN THE AFTER CONF! โ†‘ ALL THE LINKS! ๐Ÿค“
  5. #QUESTION ๐Ÿค” Iโ€™ve been looking forward so much to this

    conference! Especially becauseโ€ฆ
  6. DEEP DIVING ON CONCURRENT REACT ๐Ÿ˜๐Ÿ˜๐Ÿ˜

  7. Prologue DEEP DIVING ON CONCURRENT REACT

  8. #QUESTION ๐Ÿค” Why do we even bother discussing Concurrent React?

  9. PERFOMANCE

  10. PERFOMANCE PERCEIVED LOAD SPEED HOW QUICKLY A PAGE CAN LOAD

    AND RENDER ALL OF ITS VISUAL ELEMENTS TO THE SCREEN SMOOTHNESS DO TRANSITIONS & ANIMATIONS RENDER AT A CONSISTENT FRAME RATE AND FLOW FLUIDLY? LOAD RESPONSIVENESS HOW QUICKLY A PAGE CAN LOAD/RUN ANY REQUIRED JS IN ORDER FOR COMPONENTS TO RESPOND TO USER INTERACTION RUNTIME RESPONSIVENESS AFTER THE PAGE LOAD, HOW QUICKLY CAN THE PAGE RESPOND TO USER INTERACTION?
  11. PERFOMANCE PERCEIVED LOAD SPEED HOW QUICKLY A PAGE CAN LOAD

    AND RENDER ALL OF ITS VISUAL ELEMENTS TO THE SCREEN LOAD RESPONSIVENESS HOW QUICKLY A PAGE CAN LOAD/RUN ANY REQUIRED JS IN ORDER FOR COMPONENTS TO RESPOND TO USER INTERACTION RUNTIME RESPONSIVENESS AFTER THE PAGE LOAD, HOW QUICKLY CAN THE PAGE RESPOND TO USER INTERACTION? SMOOTHNESS DO TRANSITIONS & ANIMATIONS RENDER AT A CONSISTENT FRAME RATE AND FLOW FLUIDLY?
  12. None
  13. LONG TASKS

  14. LONG TASKS

  15. LONG TASKS

  16. #RESEARCH ๐Ÿ“š Phone users experience slow First Input Delay on

    7x more websites. โ€”โ€‰Web Almanac By HTTP Archive, 2021
  17. 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
  18. โ€”โ€‰AKAMAI AND CHROME RESEARCH, 2017 BUSINESS OUTCOMES

  19. #ANSWER ๐Ÿ’ก Thatโ€™s why we do bother discussing Concurrent React!

  20. #QUESTION ๐Ÿค” If you were to summarize Concurrent React in

    one word/expression, whatโ€™d be your pick?
  21. #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 = ???
  22. DEEP DIVING ON CONCURRENT REACT 1st/2nd/3rd ANSWERS โ† MEDALLIA SWAG

    OTHERS โ† STICKERS ๐Ÿ’… If you were to summarize Concurrent React in one word/expression, whatโ€™d be your pick?
  23. The Main Thread DEEP DIVING ON CONCURRENT REACT

  24. 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 LONG AND BLOCK OTHER TASKS
  25. #QUESTION ๐Ÿค” How to avoid blocking the main thread?

  26. TASK RUNNING STRATEGIES A B C D

  27. TASK RUNNING STRATEGIES PARALLELISM CONCURRENCY SCHEDULING

  28. TASK RUNNING STRATEGIES PARALLELISM CONCURRENCY SCHEDULING

  29. 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 ๐Ÿบ
  30. ๐ŸŽญ ACTORS WORKERS โ† EACH ACTOR FULLY OWNS THE DATA

    IT IS OPERATING ON โ† ACTORS CAN ONLY SEND/REACT TO MESSAGES โ† THE MAIN THREAD IS ACTOR THAT OWNS THE DOM/UI โ† postMessage HAS NO BUILT-IN UNDERSTANDING OF REQUEST AND RESPONSE โ† BALANCE: MOVING CODE TO A WORKER VS COMMUNICATION OVERHEAD/WORKER BEING BUSY ๐Ÿ”— SHARED MEMORY โ† ONE DEDICATED TYPE: SharedArrayBuffer
  31. ๐ŸŽญ ACTORS WORKERS ๐Ÿ”— SHARED MEMORY โ† ONE DEDICATED TYPE:

    SharedArrayBuffer โ† IF SENT VIA postMessage, THE OTHER END GETS A HANDLE TO THE EXACT SAME MEMORY CHUNK โ† MOST OF THE WEB APIS ARE BUILT NO CONCURRENT ACCESS TO OBJECTS IN MIND โ† YOU BUILD YOUR OWN CONCURRENT DATA STRUCTURES โ† NO DIRECT WAY OF WORKING ON FAMILIAR OBJECTS/ ARRAYS; JUST A SERIES OF BYTES ๐Ÿบ โ† EACH ACTOR FULLY OWNS THE DATA IT IS OPERATING ON
  32. WEB ASSEMBLY โ† THE BEST EXPERIENCE FOR SHARED-MEMORY MODEL โ†

    DOESNโ€™T OFFER THE "COMFORT" OF JAVASCRIPT โ† FASTER WHEN YOU STAY WITHIN WASM โ† JAVASCRIPT IS OFTEN FASTER AT DOM AND HIGH- LEVEL UI LIBRARIES CAN BE MORE PERFORMANT THAN LOW-LEVEL WASM IMPLEMENTATIONS ๐Ÿบ
  33. โ† Atomics โ† BuffferBackedObject โ† Comlink โ† WorkerDOM โ† AND

    MUCH MORE!
  34. WORKERS โ† GOOD FOR DATA PROCESSING AND CRUNCHING NUMBERS โ†

    HARD TO USE FOR UI-RELATED STUFF โ† HARDER THAN ADJUSTING WORK FOR A SCHEDULER
  35. TASK RUNNING STRATEGIES PARALLELISM CONCURRENCY SCHEDULING

  36. #QUESTION ๐Ÿค” If you were to summarize Concurrent React in

    one word/expression, whatโ€™d be your pick?
  37. DEEP DIVING ON CONCURRENT REACT If you were to summarize

    Concurrent React in one word/expression, whatโ€™d be your pick?
  38. Scheduling in React DEEP DIVING ON CONCURRENT REACT

  39. โ† 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
  40. โ†“ ORIGINAL RENDER TASK USER INPUT โ†’ โ†‘ HIGHER PRIORITY

    RENDER TASK โ†“ RESUME ORIGINAL RENDER TASK
  41. โ† 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
  42. PRIORITY LEVELS

  43. PRIORITY LEVELS

  44. 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)
  45. โ† 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 ๐Ÿบ
  46. โ† 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 ๐Ÿบ
  47. None
  48. DEEP DIVING ON CONCURRENT REACT

  49. #QUESTION ๐Ÿค” How do we benefit from these in our

    everyday projects?
  50. Scheduling in React [for the rest of us] DEEP DIVING

    ON CONCURRENT REACT
  51. 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!
  52. #1 HANDLING LARGE SETS OF DATA DEEP DIVING ON CONCURRENT

    REACT
  53. ๐Ÿ˜” NON-PRACTICALโ€ฆ โ† FINDING PRIMES โ† CRACKING PASSWORDS โ† SIERPINSKI

    TRIANGLE
  54. ๐Ÿ˜” NON-PRACTICALโ€ฆ โ† RENDERING MANY DATA-POINTS โ† RENDERING ON A

    <canvas> โ† PROCESSING DATA
  55. DAILY VISITORS (BEFORE)

  56. 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;
  57. 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;
  58. DAILY VISITORS (AFTER)

  59. โ† หœ100K + POINTS PLOTTED โ† SUPPORT FOR SEARCHING AND

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

    โ† SUPPORT FOR SEARCHING AND FILTERING โ† USED VIRTUALIZATION AND MEMOIZATION โ† COULD'VE USED TRANSITIONS
  61. #2 TACKLING WASTED RENDERS DEEP DIVING ON CONCURRENT REACT

  62. useSyncExternalStore() function useSyncExternalStore<Snapshot>( subscribe: (onStoreChange: () = > void) =

    > () = > void, getSnapshot: () = > Snapshot, getServerSnapshot?: () = > Snapshot ): Snapshot;
  63. DEEP DIVING ON CONCURRENT REACT

  64. None
  65. #QUESTION ๐Ÿค” How do we benefit from these in our

    everyday projects?
  66. useLocation() function Pathname() { const { pathname } = useLocation();

    return <Badge title={pathname} subtitle="pathname" />; } function Hash() { const { hash } = useLocation(); return <Badge title={hash} subtitle="hash" />; }
  67. 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
  68. SPEAKERS LIST [BEFORE]

  69. useLocation() function Pathname() { const { pathname } = useLocation();

    return <Badge title={pathname} subtitle="pathname" />; } function Hash() { const { hash } = useLocation(); return <Badge title={hash} subtitle="hash" />; }
  70. 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" />; }
  71. 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()
  72. SPEAKERS LIST [AFTER]

  73. #3 HYDRATION IMPROVEMENTS DEEP DIVING ON CONCURRENT REACT

  74. โ† 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
  75. โ† 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
  76. โ† 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
  77. SELECTIVE HYDRATION <Layout> <Article /> <Suspense fallback={<Spinner />}> <Co m

    m ents /> </Suspense> </Layout>
  78. DEEP DIVING ON CONCURRENT REACT

  79. #4 PROFILER ENHANCEMENTS DEEP DIVING ON CONCURRENT REACT

  80. TRANSITIONS โ€” INTRODUCING A NEW REACT PROFILER, BY BRIAN VAUGHN

  81. โ€” INTRODUCING A NEW REACT PROFILER, BY BRIAN VAUGHN WARNS

  82. Measure DEEP DIVING ON CONCURRENT REACT

  83. MEASURE IN THE LAB

  84. MEASURE IN THE FIELD

  85. TIMING USER TIMING ALLOWS YOU TO MARK POINTS IN TIME

    AND THEN MEASURE THE DURATION BETWEEN THOSE MARKS. EVENT TIMING EVENT PROCESSING TIME + TIME UNTIL THE NEXT FRAME CAN BE RENDERED. THE BASIS FOR THE FID METRIC. ELEMENT TIMING MEASURE THE RENDER TIME OF SPECIFIC ELEMENTS. THE BASIS FOR THE LCP METRIC. RESOURCE TIMING RETRIEVE AND ANALYZE DETAILED NETWORK TIMING DATA REGARDING THE LOADING
  86. PROFILING LONG TASKS API REPORTS TASKS THAT TAKES LONGER THAN

    50 MS AND IT'S THE BASIS FOR TTI AND TBT METRICS JS SELF-PROFILING API PROFILE SPECIFIC COMPLEX OPERATIONS AND IDENTIFY HOT SPOTS USING A SAMPLING PROFILER UserAgentSpecificMemory DETECT MEMORY LEAKS IN APPS THAT HANDLE A HUGE VOLUME OF DATA
  87. { name: "same-origin-descendant", entryType: "longtask", startTime: 1023.40999995591, duration: 187.19000002602115, attribution:

    [ { name: "unknown", entryType: "taskattribution", startTime: 0, duration: 0, containerType: "iframe", containerSrc: "child.html", containerId: "", containerName: "child1" } ] } { bytes: 1000000, breakdown: [ { bytes: 1000000, attribution: [ { url: "https://example.com", scope: "Window", }, ], types: ["JS", "DOM"], }, { bytes: 0, attribution: [], types: [], }, ], } { "frames": [ { "name": "Profiler" }, { "column": 0, "line": 100, "name": "", "resourceId": 0 }, { "name": "set innerHTML" }, { "column": 10, "line": 10, "name": "A", "resourceId": 1 } { "column": 20, "line": 20, "name": "B", "resourceId": 1 } ], "resources": [ "https://example.com/page", "https://example.com/app.js", ], "samples": [ { "stackId": 0, "timestamp": 161.99500000476837 }, { "stackId": 2, "timestamp": 182.43499994277954 }, { "timestamp": 197.43499994277954 }, { "timestamp": 213.32999992370605 }, { "stackId": 3, "timestamp": 228.59999990463257 }, ], "stacks": [ { "frameId": 0 }, { "frameId": 2 }, { "frameId": 3 }, { "frameId": 4, "parentId": 2 } ] } LONG TASKS SELF-PROFILING USERAGENT MEMORY ๐Ÿบ
  88. #PROTIP ๐Ÿ’ก Use observability services or libraries like web-vitals. But

    remember you can also create your own abstractions on top of the web + React.
  89. The Future DEEP DIVING ON CONCURRENT REACT

  90. โ† 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 ๐Ÿบ
  91. โ† useInsertionEffect FOR STYLESHEET LIBRARIES โ† THE <Offscreen> COMPONENT โ†

    SERVER COMPONENTS โ† NATIVE SCHEDULING PRIMITIVES ON THE BROWSER THE FUTURE ๐Ÿบ
  92. 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
  93. 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
  94. DEEP DIVING ON CONCURRENT REACT

  95. SCHEDULING API

  96. Closing Notes DEEP DIVING ON CONCURRENT REACT

  97. None
  98. #1 DEEP DIVING ON CONCURRENT REACT REACT HAS BEEN PUSHING

    WEB APIS TO THE FUTURE E.G. THE SCHEDULER API
  99. #2 DEEP DIVING ON CONCURRENT REACT UNDERSTANDING THESE INTERNALS AND

    THEIR RATIONALES HELPS US IMPLEMENT OUR OWN ABSTRACTIONS
  100. #3 DEEP DIVING ON CONCURRENT REACT SCHEDULING DOES NOT NECESSARILY

    MEAN BETTER PERFORMANCE ๐Ÿบ
  101. #4 DEEP DIVING ON CONCURRENT REACT THERE'S NO SILVER BULLET.

    IDENTIFY YOUR CORE METRICS.
  102. #5 DEEP DIVING ON CONCURRENT REACT THEREโ€™S A LOT OF

    INFORMATION OUT THERE
  103. None
  104. #6 DEEP DIVING ON CONCURRENT REACT ALWAYS TRY TO CORRELATE

    BUSINESS METRICS WITH PERFORMANCE
  105. Weโ€™re hiring! ๐Ÿ—บ Mostly inโ€ฆ ๐Ÿ‡บ๐Ÿ‡ธ๐Ÿ‡ฒ๐Ÿ‡ฝ๐Ÿ‡ฆ๐Ÿ‡ท๐Ÿ‡บ๐Ÿ‡พ๐Ÿ‡ช๐Ÿ‡ธ๐Ÿ‡จ๐Ÿ‡ฟ๐Ÿ‡ฎ๐Ÿ‡ฑ๐Ÿ‡ฎ๐Ÿ‡ณ

  106. DEEP DIVING ON CONCURRENT REACT

  107. None
  108. DEEP DIVING ON CONCURRENT REACT THATโ€™S ALL, FOLKS! THANKS! ๐Ÿค

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