Time Travel (Debugging) with ReactNative

One of the things I love about React and ReactNative is the emphasis on DX (Developer Experience), in addition to the amazing UX (User Experience). I was particularly fascinated by the Time Travel Debugging feature in Redux.
Being a fan of Time Travel (the last 3 books I read were stories of time travel; I am re-watching Dr. Who these days), I started experimenting with bringing true Time Travel to ReactNative. Recently, folks from the Chakra team showed off support for time travel debugging in Node at the NodeSummit. In a previous blog post, I had also explained how I was using a node process to enable VSCode debug ReactNative apps.
Putting these together, I was able to enable time travel debugging for ReactNative using VSCode and Chakra core - here is a demo.

Link: https://www.youtube.com/watch?v=waiZsNI4SYA

What is Time Travel Debugging ?

In addtition to typical debugging actions like stepping into or stepping over code, time travel also allows developers to "step back" into previous statements, inspecting state of variables backward in time. This is typically achieved by first recording user actions and then replaying them with a debugger attached.

Chakra TTD ? 

To record a new debug session in Chakra, the -TTRecord flag is passed. Due to this flag, all the states of the app at various points in time are recorded and finally written into a folder when the node process exits. The node process is then started with a -TTReplay flag that replays the actions. VSCode can attach to that node process as a debugger and has support to step back into statements, in addition to the usual debug workflows. The Chakra Core page has more information about how to get the latest builds and try it out.

Chakra and ReactNative

When the developer selects "Debug JS Remotely" from the menu, ReactNative is put into a proxy mode. The packager then simply opens Chrome and runs all the ReactNative code on Chrome. Chrome Dev tools are attached to this Chrome page and features like breakpoints or watches are possible.
In the VSCode ReactNative debugger, we replace Chrome with a Node process that VSCode can attach to, as a debugger.

Try it today

As VSCode simply runs Node, I just needed to replace Node with Node-Chakra. Alternatively, here is a version of the code extracted from the Chrome debugger. You can download this and run it using Node or Node Chakra. When starting debug from the app, all instructions are now executed on this process. There are many IDEs and tools that can attach to and debug node apps - any one of them could be used.

Check out the ReactNative VSCode extension that I am working on, or follow me on twitter for updates on this experiment :) 

Using Cordova plugins in ReactNative

A tool use Cordova plugins with React Native - link

As ReactNative is maturing into a stable platform to create mobile applications for iOS and Android devices, developers are starting to need more native modules to leverage device APIs like bluetooth or the camera. Apache Cordova (formerly called Phonegap) is a similar runtime can be used to build mobile applications, but displays the user interface in a using a WebView. Apache Cordova also has an large eco system of plugins that enable these webview based applications to call native code.
In a previous blog post, I had written about the project where a ReactNative application could use the exiting Cordova plugins to call device APIs.
The project has evolved and supports many more plugins and features. Here is a kitchen sink like application with many Cordova plugins are added to the ReactNative applications.

The project has now been updated to support ReactNative 0.19+, and can also use Cordova 6.0+ plugins.
All these changes, including the  instructions on how to add the react-native-cordova-plugin into a ReactNative project are at the README file. 

Some of the big changes include
  1. Support for plugins that run on initialization. For example, the cordova-device-plugin runs as soon as the app is initialized and makes a window.device object available, populated with attributes about the device.
  2. Added support for event listeners so that plugins like geolocation or cordova-plugin-device-orientation can now subscribe to get updates when the compass changes. 
  3. ReactNative 0.18+ changed the MainActivity and how native modules are included. These changes are now available in the plugin. 
Currently, the plugin adapter only supports Android and I am learning iOS to add iOS support too. Check out the project on github and open an issue to ask questions about the integration or to help with fixing a bug.

Using Webworkers to make React faster

Tl;Dr; ReactJS is faster when Virtual DOM reconciliations are done on a Web Worker thread. Check out the difference at the demo page

A typical ReactJS application consists of two parts - the React library responsible for most of the complex Virtual DOM calculations, and React-Dom that interacts with the browser's DOM to display contents on the screen. Both these are added to the page using script tags and run in the main UI thread.
In a blog post a few weeks ago, I had written about an experiment where I tried to run the React Virtual DOM calculations in a Web worker instead of main UI thread of the browser. I had also run performance measurements to understand the impact of parameters like node count or parallel workers on frame rates.

Recap of previous results

The frame rate numbers in themselves were not conclusive from the previous implementation. It was observed that the real benefit of Web Workers only surfaced when there were sufficiently large number of nodes to change. In fact, the performance of Web Workers was worse than the normal React implementation when the node count as small as in a typical for most applications.

Updates and new results

The reason that the Web-workers case is slow was due to the time spent passing and processing messages between Web Workers and the main UI thread. I was trying to solve this problem by trying to find an optimal batch size so that the message processing time is much less than actual DOM manipulation. While tweaking the batch size did not yield great benefits, I got a couple of good suggestions from folks on the internet.  
  1. The first suggestion was to use transferable objects instead of using JSON data to pass messages. The DOM manipulation instructions I was passing between the worker and the UI thread did not have a fixed structure. Thus, I would have to implement a custom binary protocol to make this work.
  2. The second suggestion was to simply use JSON.stringify when passing messages. I guess this is similar to transferable objects, just that in this case, it is a big blob of 8-bit characters. There is also a comment about this by one of the IndexedDB authors.
By 'stringifying' all messages between the worker and the main thread, React implemented on a Web worker faster than the normal react version. The perf benefit of the Web Worker approach starts to increase as the number of nodes increases. 

I wrote an automation script to calculate the frame rates using browser-perf, and here is the chart. The tests were run on Desktop Chrome on a Macbook pro, and a Nexus Android device.
As the number of nodes get to more than 100, the difference is not very visible. To make the difference explicit, here is the same chart with the frame rates in a logarithmic scale when running on desktop chrome.

As you can see from the charts, the React Worker version is at least as fast as, if not faster than the normal version. The difference starts to get more pronounced as the number of nodes increases.
A good experiment should be reproducible, and you can use these instructions to run the tests and collect the information, or simple use Chrome's FPS meter to see the difference in the worker and normal pages.

A real world app

While it worked well on an articifial app like DBMonster, it is also important to test this idea on typical real world apps. I wrote a todo app that also serves as an example to show the changes needed in a react app to make it work with Web workers. The changes are not many and we basically need to separate React and React-DOM into the worker and main threads respectively.

Browser Events

A web worker does not have access to the browser DOM and hence cannot listen to click or scroll events. Presently, React has an event system with a top level event listener that listens to all events, converts them into synthetic events and sends it over to listeners that we define in the Virtual DOM (in JSX files).
For our webworker case, I re-use this event listener and subscribe to all events. Thus, all events are handled in the main thread, converted to synthetic events and then passed over to the worker. This also means that all the calculations to create synthetic events happens in the main thread. A potential improvement would be passing the raw events over to the worker and calculating synthetic events and bubbling on the worker.
The other issue is about semantics like preventDefault() or stopPropogation(), as also described in the pokedox article. Responding to event in a browser is synchronous while passing messages and getting a result back from a web worker is asynchronous. Thus, a way is needed to determine if we need to prevent default even before the event handler running on a worker can tell us.
At the moment, I simply prevent all default actions, but there are two options here to ensure correct behavior. As vjeux suggests, we could use a pure function that can be serialized and sent to the main UI thread from the worker. Another option would be to prevent the current event and raise another event in case preventDefault is not called.
I am still exploring the options and as other frameworks start offloading work to web workers, I am sure we could come up with a pattern.

Next Steps

The tests conclusively tell me that Web Workers are always better. May be we are in an era where Web Workers are finally used by mainstream Javascript framework to offload all expensive computations.
My implementation may have some gaps and I would like to try it out on more real world apps. If you have an app suggestion and would like to try it out, I would love to work with you. You can either ping me, or head over to the github repo to send in pull requests !