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

React Native Internals

A01b931867096ec8874202e233279212?s=47 Simon Sturmer
PRO
July 13, 2018
110

React Native Internals

A01b931867096ec8874202e233279212?s=128

Simon Sturmer
PRO

July 13, 2018
Tweet

Transcript

  1. REACT NATIVE INTERNALS Kansas City Developer Conference 2018

  2. Hi.
 I’m Simon I run a dev team building cool

    stuff with React and React Native. @sstur_ Previously @ Facebook in California
 Currently CTO at KodeFox, Inc. simon@kodefox.com
  3. We’ll talk about a few things today. What is React

    Native What lies ahead? How Does it work? (internals)
  4. React Native is a set of tools to write native

    apps in JavaScript, based on the ideas of React. WHAT IS REACT NATIVE?
  5. • Command-line tool • npm library • Bundler • Set

    of native modules and UI primitives • Layout engine • API between native and JS • Set of debugging tools • … and more. WHAT IS REACT NATIVE?
  6. • Not the same as React on web, although it

    shares some code. • No WebView or HTML or CSS or DOM. • Does not use <div> or <span> or any of the web primitives • Does not “re-create” the platform’s native components • Not really a “hybrid” framework in the typical sense (like Ionic) • Does not “compile” your JavaScript to native code. WHAT REACT NATIVE IS NOT
  7. • Allows you to build your application 100% in JavaScript

    (or TypeScript) • Build with native components rendered by native code. • You can apply much of your existing experience from Web
 (box model, flex layout)
  8. React Native was created at Facebook with a few design

    goals in mind. WHY WAS REACT NATIVE
 CREATED?
  9. • Solve the challenges of building two separate native apps.

    • Single language and set of tooling across iOS and Android • Developer experience of web with the power of native mobile. • Leverage the core concepts developers love about React. DESIGN GOALS “Learn once, write anywhere”
  10. We want the power and performance of
 native apps with

    the awesome
 development experience of the web.
  11. • Write code, save, reload
 … like a refreshing a

    web page. • Instant feedback, helpful errors. • Simple, powerful layout system using Flexbox • Scale easily to large teams WEB
  12. • Smooth animations • Complex, natural-feeling gestures • Fast and

    responsive • Excellent end-user experience • Deep hardware integration NATIVE MOBILE
  13. LET’S LOOK AT SOME CODE

  14. None
  15. IF YOU’VE DONE SOME REACT ON THE WEB, THEN YOU

    ALREADY KNOW REACT NATIVE.
  16. …but JavaScript?!

  17. • Modern JavaScript is surprisingly fast and well optimized. •

    The JavaScript ecosystem is mature with plenty of great tooling. • React is well known for solving perf issues on the web. HTML/CSS is slow; The DOM is slow. Animations can be slow if they’re driven from JS
  18. You can achieve performance that is indistinguishable to the user

    from a native app written in Swift or Java.
  19. …but how?!

  20. REACT NATIVE
 INTERNALS

  21. HOW IT WORKS Bridge { } Native
 Thread(s) JavaScript
 Thread

  22. JavaScript
 Thread • All the code you write essentially runs

    here. • Non-blocking, single-threaded. • Intentionally Isolated; no shared memory. • Can only communicate with the native side by message passing.
  23. JavaScript
 Thread Most of the JS constructs you know and

    love: • fetch() • Promises; async/await • JSON • require() and import
  24. { } Native
 Thread(s)

  25. { } Native
 Thread(s) Use analogy of server-rendered HTML •

    Instantiating, styling and positioning native elements. • Converting Flexbox layout to pixel- based layout (Yoga). • Interfacing with the hardware (GPS, Network, camera) • Notifying the JS side about events (such as device rotation or touch)
  26. { } Native
 Thread(s) • Mostly this is framework code.

    • You do not normally write
 native code when building Apps with React Native. • Unless you’re a library author.
  27. THE BRIDGE { } Native JavaScript

  28. • Handles message passing between JavaScript and Native • Each

    message is completely serializable and the format looks like JSON. • Message passing is asynchronous. • Each message is essentially a command (method call) The
 Bridge
  29. None
  30. • All your business logic runs on the JS side.

    • All code that interfaces with hardware runs on the Native side. • Example messages from JS -> Native:
 - Placement of an element on screen
 - Sending a network request • Example messages from Native -> JS:
 - Notification of user input (touch / scroll)
 - Network response
  31. Asynchronous, Batched, Serializable This builds upon and formalizes some of

    the principles used by React on the web.
  32. This provides such a clearly defined abstraction it's almost like

    two network devices communicating over HTTP or WebSocket. In fact, you can sub out the bridge for an actual WEBSOCKET for debugging.
  33. But… The bridge is slow (relatively) The message queue can

    be a
 bottleneck.
  34. Remember, every message has to be serialized and gets put

    in the queue to be processed in batches. THE MESSAGE
 QUEUE
  35. This causes many operations to be async. Like when JS

    queries simple hardware info. THE MESSAGE
 QUEUE
  36. None
  37. Native JavaScript 1. Send message to
 request network info. 2.

    Query the hardware
 and compose a
 response message. 3. Receive response
 and pass to callback.
  38. For most tasks, this is no problem.
 The React design

    pattern is great for batching updates.
  39. Doing any of this on the JS thread: • Animation:

    updating layout every frame. • Re-rendering an element onScroll. • Gestures: swiping or pinch-to- zoom. • Basically everything you love about native interactions. THINGS THAT WILL
 CONGEST
 THE BRIDGE
  40. SO HOW THEN
 CAN REACT NATIVE BE FAST?

  41. Just don’t do animation and gesture handling on the JavaScript

    thread.
  42. IN REACT NATIVE, WE USE A DECLARATIVE APPROACH
 FOR ANIMATION

    AND GESTURES.
  43. We write code that describes what we want, not how

    it should be done. DECLARATIVE /dih-klar-uh-tiv/ adjective
  44. EXAMPLE Imperative Declarative I want a blue square on the

    screen. (I don’t care what’s currently on the screen) • Get the shape that’s on the screen. • If it’s not a square, call setShape(‘square’) • If it’s not blue, call setColor(‘blue’)
  45. Describe the animation, but let the native side calculate the

    intermediate frames. DECLARATIVE
 ANIMATIONS
  46. None
  47. ONE PASS ACROSS THE BRIDGE
 TO KICK-OFF THE ENTIRE ANIMATION.

    A single return message to notify the JS
 when the animation is done.
  48. In this context, a gesture is an animation that is

    attached to an ongoing user interaction (swipe, scroll). GESTURE VS
 ANIMATION
  49. The libraries for declarative animations and gestures are getting better

    all the time.
 
 New Hotness: “reanimated” BETTER ANIMATION
 AND GESTURES
  50. Credit: @HenryKirkness https://github.com/kirkness/interactions 60FPS
 GESTURES &
 ANIMATIONS

  51. Native JavaScript 1. Send the description
 of the animation. 2.

    Compute and render
 all the frames. 3. Get notification that
 animation is finished.
  52. THIS TALK IS NOT REALLY ABOUT ANIMATION But it’s an

    important part of high-performance mobile.
  53. TITANIUM SPONSORS Platinum Sponsors Gold Sponsors K C D C

    2 0 1 8
  54. WHAT OTHER ADVANTAGES do we get?

  55. • Excellent perf even when another thread is busy •

    Better use of multi-cores. • Clean abstractions and separation of concerns. Since all of our business logic (our application code) runs on a different thread,
  56. Since the JavaScript is interpreted, we get some other cool

    stuff. • Almost instantaneous code reload. • Over the air updates (yes, even on iOS) • Sandbox/playground to easily experiment with React Native JAVASCRIPT
  57. In fact, with Expo Snack, you can actually… • Go

    to https://snack.expo.io • Write some code • Instantly run it on your device. • … with hot-reloading.
  58. None
  59. THIS IS POSSIBLE BECAUSE Your application code is JavaScript
 which

    is interpreted.
  60. Specifically, React Native uses JavaScriptCore (from Safari) which runs on

    iOS without JIT.
  61. LET’S TALK ABOUT LAYOUT

  62. HISTORICALLY, THIS HAS BEEN HARD TO DO

  63. FLEXBOX HAS MADE LAYOUT TRIVIAL Mostly.

  64. Yoga is a library from Facebook, originally made for React

    Native. • Built mostly in C++ • Platform independent • Takes in flex properties (flexDirection, alignItems, etc) • Outputs [top, left, width, height] • That’s all it does. YOGA yogalayout.com
  65. Online Playground for Layout

  66. Flex Layout Coordinates

  67. None
  68. None
  69. LAYOUT GETS ITS OWN THREAD This helps a lot with

    smooth UI.
 Almost zero frame drops for native driven animations.
  70. In fact, there are several threads on the Native side.

    • Main Thread: in charge of startup; launches other threads, including the JS thread • UI/Layout Thread • One thread for each native module:
 network, localStorage, custom modules
  71. SO TO SUMMARIZE

  72. Your entire JS application, you can think of as a

    system that takes events as inputs and produces commands as outputs. THE JAVASCRIPT
 SIDE
  73. You can think of the Native side like the web

    browser or the render engine. THE NATIVE SIDE
  74. An asynchronous, batched message bus between the two systems. THE

    BRIDGE
  75. WHERE DO WE GO FROM HERE Have we solved cross-platform

    mobile?
  76. NO

  77. BUT REACT NATIVE IS HERE TO STAY FOR A WHILE.

  78. • Libraries will always be written in low-level, native code.

    • Application code is moving more towards higher-level, cross- platform solutions,
 such as React Native or Flutter. • More frameworks are building on the ideas of React THE TREND, AS
 I SEE IT
  79. • The next generation frameworks that replace React Native will

    probably not use JavaScript • There’s nothing about the React Native paradigm that requires JavaScript • Better, more strongly typed languages are coming about, such as ReasonML and Kotlin • Declarative is the right way to do UI and will have a huge influence on future frameworks.
  80. THANK YOU @sstur_ slides: kodefox.com/kcdc

  81. None