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

๐Ÿ‡ฌ๐Ÿ‡ท CityJS Athens 2023

๐Ÿ‡ฌ๐Ÿ‡ท CityJS Athensย 2023

โ„น๏ธ 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

May 31, 2023
Tweet

More Decks by Matheus Albuquerque

Other Decks in Programming

Transcript

  1. #DISCLAIMER ๐Ÿ˜Œ This is a deep dive for those who

    are interested in API discussions. You donโ€™t need to know all of that to be productive with React.
  2. #QUESTION ๐Ÿค” If you were to summarize Concurrent React in

    one word/expression, whatโ€™d be your pick?
  3. #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 = ???
  4. DEEP DIVING ON CONCURRENT REACT If you were to summarize

    Concurrent React in one word/expression, whatโ€™d be your pick?
  5. #RESEARCH ๐Ÿ“š Phone users experience slow First Input Delay on

    7x more websites. โ€”โ€‰Web Almanac By HTTP Archive, 2021
  6. โ† 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
  7. 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 ๐Ÿคฟ
  8. ๐ŸŽญ ACTORS โ† 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 โ† 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 โ† YOU BUILD YOUR OWN CONCURRENT DATA STRUCTURES โ† NO DIRECT WAY OF WORKING ON FAMILIAR OBJECTS/ARRAYS; JUST A SERIES OF BYTES ๐Ÿ”— SHARED MEMORY
  9. ๐ŸŽญ ACTORS โ† 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 โ† 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 โ† YOU BUILD YOUR OWN CONCURRENT DATA STRUCTURES โ† NO DIRECT WAY OF WORKING ON FAMILIAR OBJECTS/ARRAYS; JUST A SERIES OF BYTES ๐Ÿ”— SHARED MEMORY
  10. 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 ๐Ÿคฟ
  11. WORKERS โ† GOOD FOR DATA PROCESSING AND CRUNCHING NUMBERS โ†

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

    one word/expression, whatโ€™d be your pick?
  13. 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
  14. โ† 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
  15. โ†“ ORIGINAL RENDER TASK USER INPUT โ†’ โ†‘ HIGHER PRIORITY

    RENDER TASK โ†“ RESUME ORIGINAL RENDER TASK
  16. โ† 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
  17. 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)
  18. โ† 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 ๐Ÿคฟ
  19. โ† 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 ๐Ÿคฟ
  20. 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!
  21. ๐Ÿ˜” NON-PRACTICALโ€ฆ โ† FINDING PRIMES โ† CRACKING PASSWORDS โ† SIERPINSKI

    TRIANGLE ๐Ÿ˜Š PRACTICALโ€ฆ โ† RENDERING MANY DATA-POINTS โ† RENDERING ON A <canvas> โ† PROCESSING DATA
  22. ๐Ÿ˜Š PRACTICALโ€ฆ โ† RENDERING MANY DATA-POINTS โ† RENDERING ON A

    <canvas> โ† PROCESSING DATA ๐Ÿ˜” NON-PRACTICALโ€ฆ โ† FINDING PRIMES โ† CRACKING PASSWORDS โ† SIERPINSKI TRIANGLE
  23. 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;
  24. 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;
  25. โ† หœ100K + POINTS PLOTTED โ† SUPPORT FOR SEARCHING AND

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

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

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

    return <Badge title={pathname} subtitle="pathname" />; } function Hash() { const { hash } = useLocation(); return <Badge title={hash} subtitle="hash" />; }
  29. 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
  30. useLocation() function Pathname() { const { pathname } = useLocation();

    return <Badge title={pathname} subtitle="pathname" />; } function Hash() { const { hash } = useLocation(); return <Badge title={hash} subtitle="hash" />; }
  31. 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" />; } useHistorySelector()
  32. 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" />; } useHistorySelector()
  33. HYDRATION (BEFORE) FETCHING DATA (SERVER) RENDERING HTML (SERVER) LOADING CODE

    (CLIENT) HYDRATING TIME TO FIRST BYTE FIRST CONTENTFUL PAINT TIME TO INTERACTIVE
  34. โ† 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 (BEFORE)
  35. HYDRATION (BEFORE) FETCHING DATA (SERVER) RENDERING HTML (SERVER) LOADING CODE

    (CLIENT) HYDRATING TIME TO FIRST BYTE FIRST CONTENTFUL PAINT TIME TO INTERACTIVE
  36. HYDRATION (AFTER) TIME TO FIRST BYTE FIRST CONTENTFUL PAINT TIME

    TO INTERACTIVE [โ€ฆ] FETCHING DATA (SERVER) RENDERING HTML (SERVER) HYDRATING LOADING CODE (CLIENT) [โ€ฆ] [โ€ฆ] [โ€ฆ] [โ€ฆ] [โ€ฆ] [โ€ฆ]
  37. โ† pipeToNodeStream + createRoot + <Suspense> โ† REACT PRIORITIZES HYDRATING

    THE PARTS THAT THE USER INTERACTED WITH BEFORE THE REST โ† COMPONENTS CAN BECOME INTERACTIVE FASTER BY ALLOWING THE BROWSER TO DO OTHER WORK AT THE SAME TIME AS HYDRATION HYDRATION (AFTER)
  38. โ† REACT WON'T WAIT FOR HUGE COMPONENTS TO LOAD TO

    CONTINUE STREAMING HTML FOR THE REST OF THE PAGE โ† WHEN THE HTML BECOMES AVAILABLE ON THE SERVER, IT WILL BE ADDED TO THE SAME STREAM ALONG WITH A SCRIPT TAG AND INSERTED IN THE RIGHT PLACE HYDRATION (AFTER)
  39. โ† 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 ๐Ÿคฟ
  40. โ† useInsertionEffect FOR STYLESHEET LIBRARIES โ† THE <Offscreen> COMPONENT โ†

    SERVER COMPONENTS โ† NATIVE SCHEDULING PRIMITIVES ON THE BROWSER THE FUTURE ๐Ÿคฟ
  41. 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
  42. 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
  43. #1 DEEP DIVING ON CONCURRENT REACT REACT IS NOT REACTIVE,

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

    WEB APIS TO THE FUTURE E.G. THE SCHEDULER API
  45. export const Hello = () = > { const value

    = usePromise(() = > delay("Hey there! ๐Ÿ‘‹", 3000)); return <Typography variant="h3">{value}</Typography>; }; function Demo() { return ( <Grid container justifyContent="center"> <Suspense fallback={<Loading message="Loading . . . " />}> <Hello /> </Suspense> </Grid> ); } ๐Ÿคฟ
  46. #3 DEEP DIVING ON CONCURRENT REACT UNDERSTANDING THESE INTERNALS AND

    THEIR RATIONALES HELPS US IMPLEMENT OUR OWN ABSTRACTIONS E.G. FIRST CLASS SUPPORT FOR PROMISES
  47. DEEP DIVING ON CONCURRENT REACT THATโ€™S ALL, FOLKS! ฮตฯ…ฯ‡ฮฑฯฮนฯƒฯ„ฯŽ! ๐Ÿค

    ๐Ÿ‡ฌ๐Ÿ‡ท QUESTIONS? โ†‘ ALL THE LINKS! ๐Ÿค“ MATHEUS ALBUQUERQUE โ€ข @ythecombinator