Use ReactJS to Build Native Apps
twitter.com
twitter.com
This is not the DOM. This is not a web view. If you know ReactJS, you can build native apps with React Native.
Does it allow you to render native components with JSX as opposed to only DOM elements? Can you mix the two, somehow?
I dreaded my Xamarin build times..
* JS engine on a background thread
* Communicates via batched, async messaging protocol to a native (objc or android) server running on the main thread (basically create_view(), update_view(), destroy_view(), on_event() etc)
* Plug-in for React that speaks that protocol
* Tools to make cross-platform dev a bit easier (standard text component, cross-platform flexbox layout system)
* Designed to take advantage of native platform views, NOT be the next Java Swing
The issue is that it’s only width-constrained.
Anyways, flex-box is not available in IE < 10. IE10 requires ms- prefix. If React makes it available everywhere (IE8+) that will be really great.
What Apple calls "constraint-based layout" is cool, but does not follow the classical definition of what a constraint-based layout actually is. They don't use variables anywhere in the IB UI. You can only define proportions in code which is incredibly clunky.
I know one complaint among many was that wrapping native API in a new framework can limit access to functionality and customization; you're limited to the choices of the framework designer. Another is debugging is harder since native tools don't understand the framework and you're dependent on the tool chain provided by the framework makers.
TBH, I don't use React right now but this is a game changer.
Can I use the same kind of jsx I am on the web today or is there going to be something different? Will sharing components between web and native mobile apps be possible?
If it's still small do you plan on the majority of future components to be first-party or third-party (community)?
Extremely exciting either way, wish there was a livestream of tomorrow.
In short, how will it work and do you have any links we should check out, or people I can contact? The React virtual DOM has all kinds of elements that map to DOM elements, so how would it render in a native app? What about native APIs and Javascript that can interface with it e.g. like it does in PhoneGap? What is the equivalent here?
Is it like Titanium in some way?
You say this is not DOM or some hybrid solution?
Either this is too good to be true or ground breaking stuff.
Do you mean that react could completely get rid of having to write stuff in Java or Objective-C?
Yes, with React Native you'll be able to write native mobile apps completely in JavaScript.
mercury was fully decoupled from virtual-dom [0] (such that you can use virtual canvas or virtual-gl). Would be really nice if this stuff can be used by other libraries easily.
It's just you don't really need Backbone with React because plain object/array models are more convenient, and controllers aren't needed because there's no need to “orchestrate changes” between view and model. Check out Flux as an example of architecture (not a framework) that works really well with React.
In Titanium it is difficult, if not impossible without resorting to a Native plug-in (which kinda defeats the object of using it IMHO as this is not 'Learn once, use anywhere'), to re-create an interface similar to the Facebook app. i.e. the vertical scrolling timeline with embedded horizontal scrolling images in each post. (on Android it really does suck) due to issue with memory, threading etc.
So I guess my question is, is it something to that React Native could cope with, or would it potentially suffer from the same memory, threading issues?
And my guess is that at some point it has to surface, so a good architectural comparison would be fab.
Perhaps the Hyperloop/React Native race is on :-)
I'll try to address some of the other more specific questions inline.
"React Native: everything native, controlled by async batched JS put in a background thread. Learn once, write everywhere. #reactjsconf" [1]
"Fb groups app in iOS App Store is powered by it #reactjsconf" [2]
"iOS and Android native using all the same ideas as React, all the power of native." [3]
React has been gaining traction as I'm sure we're all aware, but this is next-level stuff. I'm particularly interested in how styling's going to work; if this is really translating into true native stuff then there must be a CSS-analogue?
[1] https://twitter.com/AnnaPawlicka/status/560505089207463936
[2] https://twitter.com/floydophone/status/560504204343521280
[3] https://twitter.com/voodootikigod/status/560503641920921600
cannot wait for more details.
So all the good bits of CSS without any of the bad - including browser compatibility problems?
Doesn't explain stuff like fonts & colours though...
https://twitter.com/andy_matuschak/status/560511204867575808
* Write JS as usual. Write React as usual, but don't use the DOM JSX elements (or the React.DOM) factories - instead use the new 'NativeView' elements.
* The code you write runs in a Javascript interpreter on the background thread.
* The NativeView elements communicate transparently with a native server running on the main thread, which renders and fills native views based on the instructions sent.
* The JS runs react the usual way - I'm assuming the tree reconciliation happens the same way as well - the diff instructions are just sent to the native view server.
They claim perf is fine though (e.g. because render is always async, app code is always in background).
We shall see!
That said, their success (over something like node-webkit + react) will definitely depend on how well they match and integrate the native APIs.
"The virtual dom is an implementation detail of React.js. React Native demonstrates that many rendering contexts are possible."
This was kind of the exciting point all along :). DOM just happens to be the output of a function that people are most interested in at the moment. but people have been talking about using it with canvas and other stuff, too. It's a generally-useful way to map functional data to render-trees.
I this this is a great mentality over the classic write once run everywhere approach.
We're currently building a native cross-platform desktop email client in React + Flux on Atom Shell. As Nilas thinks about mobile and other platforms it's clear that the interaction design and information architecture are radically different. While some code should be re-used most shouldn't. Having a reusable architecture and way of building apps is definitely the better way to go.
I can't help but think about that other chestnut, "A determined programmer can write Fortran in any language."
Of course it makes sense to apply a pattern that you know worked great in the past. The tough part is deciding when it's worth trying something else.
So, as I understand ReactJS invokes a render() method defined by the user (programmer), and the result of that is diff'ed to previous results of the same method, and as a result, the DOM is modified.
I can understand this, but... The DOM is already incrementally rendered by the browser. That is, changes to the DOM are not direct, but are performed by the browser in a way that is as efficient as possible. So, why the need for a render() method?
Also, the render() method itself could be quite big and thus could take a long time to run, and almost completely nullify all advantages of incrementally updating only the display.
So, as you can see, I'm a bit confused...
For instance, if you add a <button> to the DOM, it will stay there forever. On the other hand if the next call to render() no longer includes the <button> then React will do the work of removing it from the DOM.
1. The virtual DOM that render deals with is several orders of magnitude faster than the real DOM, so you need to have thousands of elements before it starts taking longer than making the one change to the real DOM for the one element that changed
2. You can skip calling render on subcomponents that haven't changed, so while updating a list of 10000 elements where one has changed would require iterating through 10000 elements, updating a list of 100 elements that each contains 100 elements where one of the bottom level elements has changed would only require iterating through 200 elements.
As far as the render method being big, the premise React is built on is that the virtual DOM is much faster than the real DOM. Test as necessary for your own comfort / use cases. I personally trust the testimonials of people smarter than me that aren't the React team also feel this is true and are making real changes to their products based on that. I also trust my own experiences that the DOM is slow :)
Nothing to be confused about, you have a valid hypothesis: "Rendering and Diffing in Javascript is slower than DOM manipulation". However, all hypothesis need to be experimented before having any real meaning.
It just happens that testing this hypothesis and finding it invalid was the foundation for React.
Watch this video[https://www.youtube.com/watch?v=XxVg_s8xAms] I think it does a good job discussing this hypothesis and why they chose not to worry about it.
Now for a certain value of N, things will become slow, unresponsive. I'm guessing now that this value of N is above the value where the browser cannot handle this number of elements anyway. Is this correct?
PS: I understand that it is possible to completely optimize the listbox case. But that is not the scenario I'm interested in. I'm interested most and above all in the typical use-case. I'm just using a listbox as an example here. Just replace it by any other sufficiently complicated and customized UI component if desired.
Of course, in your example, there is a point where N gets so large that it poses problems. This is true whether you're using the raw DOM or an abstraction like React. The solution is the same in either case - cull non-visible elements from the render tree (again react makes this as efficient as possible).
EDIT: it's also worth noting you can skip updating entire subtrees in React with shouldComponentUpdate hooks. This avoids the case where you go through the render/diff cycle and it turns out there is no difference, and so nothing to update. Paired with immutable data structures this method can be a simple reference equality check (shallow equals) oldState !== newState, and therefore can really get the most efficient rendering possible
So say you're rendering some long list of items. Because react is just plain JS (no templates!), you will map the array of items to components in your render. You give each item a key so that react can reconcile components across renders. If component with same key is returned from render next time then it's kept in the DOM (and any updates applied), if not then it's removed. So the involved part becomes determining what is visible or not, and then slicing your list of items to only map a subset. This is the more involved part. I haven't built anything like this myself, but I'm guessing it basically boils down to: listening to scroll events on container, determining y offset, get height of contaoner and height of elements, use that to determine which items in list should be mapped to components in render. That bit is the same whether react or not.
See James Longster's epic blog post "Reducing User Interface Complexity, Or Why React Is Awesome" [0]. Where he details this kind of approach with his for-demp-purposes-only react-like lib.
[0] http://jlongster.com/Removing-User-Interface-Complexity,-or-...
If I get this clearly, then still:
render() -> returns N items every time it is invoked
And React will diff those N items against the DOM (using a key) every time an update is required.
So, to me it appears that still O(N) amount of work has to be done every time something small changes in the list.
This is not necessarily a bad thing. But here we assume that doing render() is faster than actually building the DOM from scratch, even though they have the same computational complexity, O(N).
Anyway, I'll have a look at that link. Very interesting, thanks again.
also remember big-O notation doesn't really capture the essence of the problem here. looping through and querying N DOM elements is probably orders of magnitude slower than doing the same with N objects in memory
The browser tries to batch updates as efficiently as possible, but because of the model there are limits on that, reflow and layout thrashing are easy pitfalls to fall into for instance. React's model obviates these issues so the system can make significantly more assumptions about what is happening, and it can combine and batch more aggressively.
Furthermore, React's updates can trivially be delayed as much as necessary (in browsers, usually to sync them with the next repaint using requestAnimationFrame), not so for DOM mutations.
> Also, the render() method itself could be quite big and thus could take a long time to run, and almost completely nullify all advantages of incrementally updating only the display.
It could be but it usually isn't, and more importantly for these cases (and others) the system can be told that there's no need to re-render the component (`shouldComponentUpdate` in react), the previous result can be reused as-is.
For "pure" components (which simply map application state to render state) it's easy to implement, and downright trivial when using persistent datastructures: it's just an identity check (which is why systems built from the ground up on persistent datastructures like clojurescript/om or elm.html are faster than "naïve" react OOTB: they can assume components are pure, will only use their parameters/state to generate UI state, and that said parameters/state hasn't been screwed with; React being a more general-purpose JS library can't afford to make these assumption, it has to be opted in explicitly)
Edit: looks like this isn't hybrid as I assumed but truly native
Well on second thought I guess Appcelerator Titanium does something similar. So it's native UI only, but with the added overhead (JS interpreter + bridge, larger binary size, slower startup, etc.).
Um, why? They already have JavaScriptCore (it's an iOS API).
I tend to prefer native interfaces over web interfaces, but found it really bothersome to have to work with native toolkits. There's stuff like tint2 (https://github.com/trueinteractions/tint2), but it's still not stable enough, IMO.
This is HUGE. I'm extremely excited to try this out. Being able to write the interface with JS/JSX, and then switch between JS and native code as you see fit or the need arises is truly the best of both worlds. For a lot of problems JS is not your bottleneck, but if it does become your bottleneck you can rewrite it natively!
The problem with "old school windows message loop" is the "windows" part (not because I don't like windows, "mac" or "linux" or "freebsd" or "solaris" could all go in there). Why haven't we abstracted presentation (functionality is a harder/more nuanced proposition).
Now we want JS and don't want to deal with gross native APIs. Perhaps it's not the same "we", though I personally am very excited about this. I love JS and I think React's ideas are the right ones for building UIs.
Hopefully, we will come to view manual NSView slugging in the same way that we'd now view building a single page webapp entirely with jQuery.
I get it, HTML can replicate performance of native apps to a certain extent now, but it's also bound by restrictions that native apps aren't.
Speed of innovation being one. HTML5 is a large ship that takes a long time to evolve (in comparison). iOS and Android aren't, by the same means. Particularly iOS since Apple has a habit of introducing backwards compatibility breaking new features.
I don't understand fully how hybrid made apps will ever be able to properly compete with a native platform for this reason alone, not mentioning some of the other problems that plague hybrid and middle ware apps.
I'd bet Angular going Native first, though, I guessed it was coming with 2.0
Looks like it's not being open sourced for a while, but apparently the attendees are going to have some hands on tomorrow.
2015 seems like it's shaping up to be the year of React!
Something needs to replace AngularJS I guess, until the next big thing.
From an architecture point-of-view, there is ReactCocoa.
If you already know ReactJS, then it'll probably be a lot easier for you to learn React Native than Swift or Objective-C.
If you are working on a team with primarily JS developers, React Native is probably a better choice to go with.
Will this cause Swift to be irrelevant? Probably not.
--
If you are learning iOS and doing production / client work, you should be aware that using a third party framework could actually break your app. I'm interested in React Naive, but also very weary about it. Facebook released a framework called Three20 back in iOS 2.0/3.0 days and abandoned the project shortly afterwards. Of course being open source there is bound to be people who take over the project, but it's something to think about.
## Architecture
Both Titanium SDK and this Native React thing do have a JavaScript runtime behind the curtains.
Both frameworks will run the JS runtime on the background, on a different thread from the UI. This is incredibly important to remind.
Titanium SDK follows an OOP-ish, imperative approach. You create views using factories (`Titanium.UI.createScrollView({ })`) and you add those views to parent views (`parent.add(child)`). This is very similar to a browser DOM, and in fact it’s cumbersome to work with. They built an xml preprocessor called Alloy which does a better job at exposing the view hierarchy right in the source, but it just compiles down to JS, `create()` and `add()`.
This is important for the evaluation at least for the following reason: every time you update a property on a view (actually on a proxy object to the real view) you’re crossing the bridge and you have to pay that penality. The bridge is the void between the JS runtime’s thread and the main, UI’s one. This is incredibly painful when trying to do JS animations, sometimes if you’re not careful you can get hurt very badly. You can still do great things, but it’s way better to use the native `.animate()` methods, which cross the bridge only twice (at start, and at the end as a callback invoking).
On Native React you should not have this kind of problems because changes will be batched and updated on a update loop basis or at least debounced. Or at least optimized in some smart way. I believe.
## Layout
One big problem will be the layout. Given that they don’t want the developers to understand every layout system every platform provides, they have to normalize it somehow. Titanium SDK has it’s own layout system, incredibly easy to understand even from a web-only dev experience:
a) by default everything is absolute positioned,
b) you can get a vertical flow layout by setting the 'layout' property on the parent view or
c) you can get a horizontal flow (inline-block-ish) by setting 'layout' to horizontal.
Native React will probably follow a more intimately web-ish approach, just look at this JS/C/Java implementation of the box-model and flex-box specification by Facebook itself [1]
[1]: https://github.com/facebook/css-layout
## Support and limits
Titanium SDK is always criticized for being to limited in what you can do with it. This actually comes from two different issues:
1) they have to (almost) manually implement every API you might need, by proxying from native-land to JS-land;
2) they have to follow every release of the platform’s SDK;
3) you cannot just put native code along-side your JS code, so you cannot go where they didn’t.
Let’s see how Native React will solve this issue.
Titanium SDK is undergoing an heavy lifting refactoring to solve exactly this issues. The project is code-named Hyperloop and is already working behind the curtains for the Windows 8 version of the SDK.
## Conclusion
Because I shamelessy want to karma-drift this topic, I’ll stop here.
It’s interesting, but until they show us some (native) code... it’s just ideas.
Follow me on twitter (@_pier) and github (@yuchi) for Titanium related stuff.
Also my company, SMC, does a lot of great opensource things for Titanium (on gh we’re @smclab)
1) How do they access the native API?
If there's no abstraction, just a translation, then the apps must be different for each platform. If there is an abstraction, then how much of the native platform do they cover? It can't be 100%, and the native APIs change with every OS version. Basic calls are easy, integrating things like device keychain, intents, and services are not so easy -- we learned this with Titanium.
2) How will React Native do cross-platform local data storage?
Being able to easily import, retain, and sync remote data is an absolute need for today's apps. Titanium uses SQLite on both sides, and has modules for more (like TiTouchDB). Not abstracting data storage would be a major mistake IMHO.
3) Can we use standard npm modules?
JS's killer feature is the module ecosystem, it's no good having a JS engine if we have to reinvent common modules to match a new API. V8 is the gold standard here, fingers crossed.
4) Debugging?
Speaks for itself. Debugging both JS and native code together bridged from a device is hard. Hopefully they are adapting existing tools and IDEs like node-inspector and Sublime Text.
BTW, did you have a look at titaniumifier? (https://github.com/smclab/titaniumifier) it’s a tool we built to port node packages to titanium (a declination of browserify, actually).
Did you feel that JS had hit it's limits with rendering and wasn't strong enough for mobile sites/apps?
Looking forward to hearing more about React Native!
Very excited for this. I have been looking at React for a while, now it's certainly time to take a plunge.
This announcement is about replacing html elements (div, h1, img, etc.) with native elements. Should be faster going native than via web elements.