Does React Native utilize a 'virtual DOM'? - reactjs

I'm trying to figure out how React Native works under the hood and something that I'm unsure of is if React Native utilizes the so-called 'virtual DOM' that React uses. I'm assuming that React Native somehow keeps track of changes to the state of the application and then does the least amount of work to get to the new state, i.e reconciliation in React. I understand that there is no real DOM on the mobile side of things and that React Native invokes native API's to render/re-render views, but...
Could one say that React Native also uses a 'virtual DOM', and if not, how would one put it into words?

UI rendering in React
Like the Real DOM, the Virtual DOM is a node tree that lists elements and their attributes and content as objects and properties. React’s render() method creates a node tree from React components and updates this tree in response to mutations in the data model, caused by actions.
So whenever anything may have changed, the entire UI will be re-rendered in a Virtual DOM representation. The difference between the previous Virtual DOM representation and the new one will be calculated. The real DOM will be updated with what has actually changed.
UI rendering in React Native
Those React-Native components map the actual real native iOS or Android UI components that get rendered on the app means React Native uses native API for the rendering of components on mobile. React Native uses a shadow thread that performs layout calculation using YOGA.
In case of any change in the component state, It will calculate the changes in the background using shadow thread then update the UI threads.

2022 Update
As React Native has changed a lot in recent times and will change a lot in the near future, I thought it's timely to update this answer:
New components to understand:
Hermes:
React Native team developed their own Javascript Engine in C++, called Hermes. If enabled, Hermes will be shipped with your app as a context for executing Javascript (instead of JSC), promising to make your app's bundle smaller, and your app's execution faster.
JSI (Javascript Interface):
It is a unified, lightweight, general-purpose layer for (theoretically) any JavaScript engine. It's implemented in C++, just as the engine, but decoupled from the engine. This makes it possible to hold references of native objects on the JS thread, eliminating the need for the bridge, thus eliminating the need to stringify everything and making React Native way faster altogether as the stringification is the bottleneck currently. It also makes it easier to switch between JS engines. As JSI is developed in C++, it makes it easier for developers to share native code between Android and iOS. For example, you can develop native code in C++, call it both on iOS and Android from Javascript through the help of JSI. Both platforms can execute C++ code, iOS can use it really easily through Objective C as it is a superset of C. Android needs a bit more work with the help of Android NDK (Native Development Kit) and JNI (Java Native Interface, responsible for Java <=> C++ translation).
Bridge will be split into two parts, read more:
Turbo modules
This is a new way of interacting with the native side, interoperable with JSI. It allows lazy initialization of packages, thus making the startup time of apps having lots of native dependencies way shorter.
Fabric renderer
Re-architecture of the UI manager, that is interoperable with JSI and Turbo modules. Instead of the Shadow Tree (or Shadow Thread) that was formerly used for calculation the layout of elements (it was coupled with the bridge), Fabric makes it possible to use the new powerful JSI features to render the ui without having to stringify anything. This will deliver truly native-like performance.
New answer for the original question:
React Native uses Fabric as a renderer, which lives in the C++ world (UI thread), has a reference to the virtual DOM, that's created by React in C++ and eliminates the need for the shadow thread as objects will be shared between the UI (native) and the JS threads. So once you click a button, React can mutate an object that it has reference to (that holds the virtual DOM), which is shared with the UI thread, that will instantly update in the UI thread, updating the UI of the app.

Related

Can I use PreactJS with React Native using preact-compat (Or using any other method)?

I've been working with react and react native for a while and there's a library that caught my attention: Preact. I learned it (that being a react developer was not difficult), I did some PWA's to practice (Copying medium-sized projects that I've done in the past) and, if you know what Preact is, it goes without saying my impression. It seems incredible to me. My question is: is there a way to work with react native using Preact? Maybe with preact-compat?
Not out of the box, no. See this discussion from GitHub
The short answer is: use a native wrapper that exposes DOM.
The long answer is that there are woefully few options for this. Some time ago, I had begun building a DOM interface to React Native, but I have no experience with React Native whatsoever and I'm likely not the best person to do that implementation.
I do know that folks have used Preact with NativeScript and had some success: NativeScript doesn't expose a Web-compatible DOM, but its UI primitives are still quite easily mapped to DOM primitives:
https://github.com/staydecent/nativescript-preact
https://github.com/NathanaelA/nativescript-dom/blob/master/src/dom.js
It would also be relatively easy to implement a nativescript-preact using the source of nativescript-vue, which implements a simple DOM on top of NativeScript's UI components that Vue then renders to:
https://github.com/nativescript-vue/nativescript-vue/tree/master/platform/nativescript
It's also worth noting that preact-compat is the legacy package, used for Preact 8.x and prior. preact/compat is where you'd get compat going forward.

React architecture for a huge business application

So we've recently picked up React in our company as the front-end technology to build our huge business web application. By saying recently, I mean we don't have any previous experience with React (we have a huge background of AngularJS), and by saying huge application, I mean it's really huge and very dynamic with lots and lots of different pieces and functionality.
Because we will have a lot of huge components that all play a very important role and have complex logic inside them, and because we want them to be easily pluggable and reusable, we want them to be as isolated as possible from the outside world and other parts of our application, because otherwise because of their size and complex functionality it would be pretty much impossible to develop and maintain them. That's the reason why we have decided NOT to use Redux, at least in the beginning, while we are developing just the separate components themselves, because it compromises component isolation and makes the whole application data flow logic impossible to understand when there are so many complex components. Although I believe our choice could be wrong, because as I've already mentioned, we have no experience with React.
As I've already mentioned, the application is very dynamic. By that I mean that components are actually rendered by data. We use various configuration provider classes that interacts with our API endpoints to get the pieces of our application's configuration, like configurations of navigation, pages, various forms, lists, etc., and then try to render components that are read from that configuration.
The problem is, after a couple of weeks struggling to get the momentum with React and discover the right patterns and common solutions to our problems, we've been talking in our crew, that maybe React is not the right technology for us, as it's a UI library, not event a framework, and it doesn't help us a lot, but just adds its rendering rules that we have to break at times to achieve the dynamics and component independence we want.
Considering the component isolation and data flow management, I personally have heard that there is a language for front-end development Elm that has pretty robust data flow architecture where each component has its own model that is separate from others, but I don't know whether it's worth a try, as it may fall behind our big requirements pretty soon too.
The reason I'm writing this question here is that I hope to get an insight from people that have a solid background on working with huge front-end applications. I'd like to know whether it's possible to develop such an application with React, whether React is suitable for such complexity and dynamics, whether we really need Redux or something else, what path, practices, ideologies should we follow. If you understood my question correctly, it's more the architecture side that we are struggling with, than the technological. Maybe we are just walking the path that leads to more and more struggle and complexity but not towards production.
There is absolutely no question that React/Redux can (and is widely) used to develop the kind of applications that you describe. Nothing in your description makes what you are building so unique that it excludes React as a platform for building it. We are actively working with a large enterprise customer who is building their entire front end - with 100 + SPA (Single page applications) in React. This is a team of over 100 developers over a 2-3 year project.
The way we structured this has been crucial -
First, you want to choose a UI component library. A few examples below :
MaterialUI - https://github.com/callemall/material-ui
React Strap - https://github.com/reactstrap/reactstrap
React Bootstrap -https://github.com/react-bootstrap/react-bootstrap
Khan Academy React Components https://github.com/Khan/react-components
https://github.com/elementalui/elemental
We basically took one of these and built a component library off of them, because our components are very custom styled.
Second, we created a modular architecture, where each module (SPA) is an npm package with a main container component and redux store.
Finally, we have a central server package, where each of the modules is registered. The server package is responsible for authentication, authorization, logging, routing, etc.
The essence of this answer is not to advise on how to structure a large React application, but to let you know that React can be (and is being) used to develop applications similar to what you are describing.
I'm at the similar situation right now. I have a background in large desktop applications (ERP, LOB - WinForms, WPF) - 1000+ modules, very dynamic (more than 70% of the UI was generated by input data/configuration), adding new functionality was just about extending some configuration (without touching source code).
I'm deeply investigating current web technologies and I'm more and more convinced that React is not a good fit for that. React really shines in small/middle size applications where you (and other team members) develop every page/component 'manually' (not dynamically generated) and you want to have one global state. But it doesn't help you with building large scale application out of the box - it is only UI library (so no support for modules, routing, forms, binding, http requests, static typing (typescript), etc.) and to my surprise, there is no support for style shadowing/encapsulation (you have to integrate, for example, CSS Modules, by your own). And at the end, you have to constantly bother with libraries versioning (to make them always work together is truly time and energy consuming).
I have a great experience with Angular 2/4+ and I think, for now, it is the best technology for that kind of the applications (if you know WPF, it is very similar). It is a full framework, which is prepared to the scaling out of the box. You can split your app into independent modules (specifying which components will be visible to the outside world), every component has public api (statically typed, inputs/outputs) and encapsulated css styles (there is no interference between others).
For the global state (logged in user, global configuration, etc.), you can still use library ngrx/store (which implements Redux pattern and comes with extra nice things, like 'effects' and integrates really well into Angular ecosystem).
I tried to do in Angular really crazy stuff (dynamically generating the whole application from backend configuration) and everything worked perfectly, as expected.
You nailed the issue in your question- react is a view library, not an application framework. The real question is whether React+Redux(or other state management system) is appropriate for a large LOB app.
I will share some insights from our team’s experience in this realm. Large LOB apps have been developed using the MVC/MVP/MVVM design patterns for decades. These are tried and true patterns that ship software. Couple that with dependency injection and you have a modularized, testable, maintainable application. AngularJS (2.0+) is founded on these principles and leverages them deeply. For this reason we use AngularJS for all of our enterprise line of business apps.
React on the other hand is a lightweight, spritely view render that is awesome for smaller applications and client facing pieces (for example taking a dynamic survey or a simple dashboard). We often turn to React and VueJS here because the full AngularJS stack is way overkill and too heavy.
Getting started writing more complex apps in React can really be a struggle, I know exactly how it feels!
As you say, React is a UI lib and not an event framework. That's why you typically need a library to handle events, for example Redux. You clearly state that you decided not to use Redux (you even used capital letters for not :) ). I would take a step back if I were you and reconsider that decision. You say the reason for not using Redux is that your cannot keep your components easily pluggable and reusable when using Redux. I would argue that is not true. Redux is totally decoupled from your React components. Redux only handles receiving events, and managing state. From the React components point of view, it just receives data in props and sends events by calling regular functions. It's possible to still unit-tests, reuse, etc.
I would suggest you take another look at Redux with this in consideration. Happy to help if you have more questions!
React , Redux will make things easier because When it comes to
complex applications you can create Well structured data object. then you can manage the Complete UI through React and its
Materials ... There are some reasons Why this is right choice
State Management ,
Tree Structure data handling,
Reduce the code,
You will be knowing where the changes made (Actions, Reducers)
Your Component will only taking care of UI things
The things that you have to do is Structuring your data
Completely understand your feelings when you start with React and Redux. We were in the same situation when we started with React in our company. At first React has different approach than other frameworks. Yes of course it's not framework, it's just library. You have to start thinking in React way and that is: React components just render state (It's like you render scene on your graphic card at first you have to prepare scene then you are able render), all what component can do is dispatch actions, or better call just action creators.
You need some smart way how to store state in that point I will suggest use Redux.
We also use TypeScript with combination React, Redux. you have to write more code than pure JS but static type control is priceless when you work on large project.
Separating components logic is native approach of react ... you have to separate logic write "Dummy components" and then reuse this with connect. Or passing values as props.
We are using Thunk middleware as action creators it's good because connected component will call just method and logic is in action creators. You have access there to whole state of app then you can fetch something and base on result you can dispatch different actions.
What I like on react/ redux is how to implement async calls etc. First design component to map all states
1) like I have no data
2) data loading
3) loading done
4) loading error
For that you need only one semaphore in you state and a few checks in render method. Then one action creator that will load data and base on progress dispatch action that describing progress.
What is also cool that in react/redux app you have single data flow it's good when new dev jump into project.
For UI we are using Material UI, yes this framework has some problems but nothing what you will not able to deal with.
We are using also Router for navigating in app.
In the beginning I will avoid server side rendering because it will much easier for you start just with client side rendering and with initial state.
When we start for us was useful this template where everything works in one project JavaScriptServices
Then off course great Abramov tutorials.
For design components very useful Storybook
We can write why use or not React for long time ... but What I can say ... for us it was good choice, with some pain in begging but now we have good payback.
We started a large scale business application using Reactjs as frontend technology.
We have over 30 people in the team and we have over 15 modules in our product.
My approach is to the project is developing a common react project that handles only the Authentication, authorization and routing of the application and all other components developed as separate npm react libraries.
To develop the libraries I used https://www.npmjs.com/package/create-react-hook
This library generates the template with an example app which can use to test our library.
Following is the structure of the project
--Library 1 ( Developed using create-react-hook )
--Library 2 ( Developed using create-react-hook )
...
--Library n
--Common Container App (Developed using create react app and have used all above libraries using npm install)
The main advantage of this approach is developers can focus only on their npm packages and they can develop and test relevant component(s) separately.
The deployment also becomes very easy because we can just update npm package of tested version and rebuild the container app and do the deployment without affecting any other part of the application.
We are using this for several months and running the project with a large team without any issue. I think this may be helpful to anyone else too.
So this is just to share my experience working on an enterprise react application that is in production for years in several banks. yes, you heard me right. Now you can imagine how huge the application will be if it's related to fintech (I know it's not always the case). we have huge modules (70+) with a complex logic that pretty much handles a lot of the work that a bank needs. Modules are both isolated and re-useable. I am going to give an example of only one module so you can imagine the size of each module.
Card Production Module
Bulk Card Generation
Bulk Card Export
Bulk Card Request
Card Operations
Card Operations Approvals
Card Printing
New Card Requests
Pin Generation
Pin Printing
This application is a product, not a project and as a product it is configurable. Even the UI is configurable. I have been working on this application as a full-stack developer. Since it's pretty old the state management library that we are using is flux. With state management, the development speed is a little slow but the tradeoffs are better with us not being worried about state management. By far the application has been able to handle huge changes and things which seemed unachievable. Stability has also been a key element throughout this period.
On the back-end, we have Restful services build using Dot Net which supports both MSSQL Server or Oracle depending on the client's needs/feasibility.
After countless react.js projects, I summarized a domain oriented and practical architecture in my blog post.
It is the absolute best practice that I applied many times, enjoy:
http://denislutz.com/domain-architecture-for-react

Can react js web code be used for building mobile apps using react native?

I am working on a pet project ( web application ) and I was wondering if I should use react because it would be easy to create native apps from this code (in future if I need to).
And if the answer is yes, what are the best practices to follow for
most resuse?
If the answer is no, can you recommend an alternative?
Some more information about my situation.
I am relatively new to react and my alternative will be good ol' html with bootstrap and jquery. I am considering using asp.net mvc and web api.
Sharing app logic between a React Web app and a React Native app, while keeping the individual component rendering unique to each platform is possible!
In my opinion, it is a great option we have available. I will give you an overview of the approach and a few advices.
In an ideal world, we would be able to share 100% of the code. As far as I know, that isn't possible, but still we can share a lot of the code. Although React Native is like React, it is very important to note that the rendering code is different. Instead web things like <div> or <span>, you use React Native components like <View>, <Text> and other built-in components.
However, the business logic in most cases is just JavaScript though and that's one of the important things which we can share!
The plan
Based on the Flux architecture you are using, it would mean that your store(s), reducers, actions would be shared code, as well as most of the business logic (inside services or whatever) and the constants and utilities too.
The UI layer would then be written specifically for each native platform using React Native and for web using React. Not only because it’s necessary to replace the HTML elements with React Native components, but also because the components will probably have a very different behavior on the mobile app.
Some General Guidelines / Advices
Consider a good architecture and code structure in order to share as much code (and application logic) as possible. Try to separate the UI presentation components (which will be different for each platform).
Take a look at the JavaScript Environment specifics in the React Native docs. When using React Native, you're going to be running your JavaScript code in two environments:
On iOS simulators and devices, Android emulators and devices. React Native uses JavaScriptCore which is the JavaScript engine that powers Safari. On iOS JSC doesn't use JIT due to the absence of writable executable memory in iOS apps.
When using Chrome debugging, it runs all the JavaScript code within Chrome itself and communicates with native code via WebSocket. So you are using V8.
While both environments are very similar, you may end up hitting some inconsistencies.
Consider the different strategies for sharing the code. In order to accesses shared code, the apps you're building doesn't have to all live in the same codebase or git repository.
More realistically, you would have two or more projects hosted separately, so an npm package is one of the easiest ways to share code between them.
This is easy as making a new package and setting it as a dependency inside each of your projects. For the path to the shared project, you can use a git repository rather than pointing to a public package on npm.
Even though you're building only the web app now, you could spend some time thinking about how you could generalize some of the shared code, so it is easier to re-use it in future.
It's possible and viable. You must have a view for each platform (web/android/ios), because each one have your components..
The business logic must be out of the view. Use flux can easy your project with native, because the it move the api interaction to a data layer, letting the view be just a view.

Between NativeBase and Shoutem, which is best to use for React Native?

I find that there are 2 UI components for React Native which are mostly used. I want to use one of them. Which one of them is more easy to use and customizable ?
Currently, there are 3 main UI libraries:
Shoutem UI Components
React Native Elements
Native Base components
Shoutem UI components are actually only one part of Shoutem UI Toolkit, which includes:
UI components - customizable set of components for RN applications
Theme - style your RN components on one place
Animation - set of declarative animations
UI components come with the predefined beautiful design, so creating good looking applications is as easy as simply c/p-ing the component's code. However, they can be fully customized with a theme from one place, so you can achieve the separation of concerns for your components. Animations can be used in similar matter, too.
To see which kind of UI components are there, include <Examples> components in your screen, as described here.
React Native Elements simplify the usage of common components in React Native. Native Base does that too, allows you to customize them and has a better documentation than React Native Elements.
Disclaimer: I work at Shoutem
All the above three libraries are good and serve their own purposes. It totally depends once after you use all of these.
NativeBase is a mobile application development framework; builds a layer on top of React Native that provides you with basic set of components for mobile application development which helps you to develop world-class application experiences on native platforms.
NativeBase gives you the potential of building applications that run on iOS and Android using a single codebase. It eases out your development.
Since NativeBase is built on top of React Native, hence with any component you can pass the style property which will be merged to the default style of that component. This also goes with the callback events. Highly customizable with the theme from one place.
All this is neatly documented by NativeBase. Docs of NativeBase gives you complete information about its usage with sample output, its replacing React Native element, how to style each component, how to customize theme for each component, many more.
Also that NativeBase is being rewritten to enhance its ease of use. To be released very soon.
Go ahead and try NativeBase!
Checkout the working demonstration of NativeBase components in one single kit NativeBase-KitchenSink.
Disclaimer: I work at NativeBase
Both are excellent. Shoutem has some pretty cool animation transitions. You can't go wrong with either. My advice is to review each and pick the one that either feels more right or matches your requirements best.
And don't forget to check out React Native Elements too
You can either use NativeBase or Shoutem UI. Both are slightly different than each other. NativeBase is designed over platform recommendations and inspired by Ionic whereas Shoutem has it's own fluent and clean design.
I've played around with native-base and Shoutem UI. Both of them fully customized.
I like Shoutem than the other because it has more feature, animation, extension, builder, etc. But unfortunately, Shoutem UI currently doesn't support the latest react-native (>0.40) and expo(> 15.0). So I hold my plan to use this for production.
I think this is because the latest RN deprecated NavigationExperimental and
Expo SDK use react-native-svg >= 5.2.0. CMIIW

React Native cross-platform codebase

Facebook has said that React Native builds on the principle of learn once, write everywhere, and that its goal is not to write cross-platform code.
NativeScript, which is pretty similar to ReactNative in the sense they both use Node.js, do offer the ability to share the same code over several platforms by writing platform specific code in files that uses native components that cannot be shared. It does that by simple naming convention, e.g foo.ios.js.
Since Facebook has not yet released their code for React Native for other platforms than iOS. Is this something they will likely support in the future?
I think there are far too many differences between Android, iOS and Web that it makes little sense to build common codebase for the whole projects. Android version will have not only native components, but also the logic of application screens and navigation will be different (iOS/Android/Web have all pretty different navigation patterns). Also there are many native components as part of the iOS/Android projects and they impact how application is started/debugged etc. so probably it is much better to keep Android and IOS parts as separate projects.
How I understand (and sympathise with) Facebok model:
Whenever there is a common functionality (in javascript) that you can separate out without dependency to react-native views, they will do it as separate component that can be reused across web/iOS/Android. For example they have relay library built for web Facebook. It abstracts away access to open-graph data on Facebook servers - the exact same relay library can be used in either environment as it has no dependencies to views, application logic and react as such.
I very much concur with that approach - the best way to do cross-platform is to follow the same practice:
make something work in one of the environments
make it separate, single-purpose library without dependencies to react, views, navigation logic.
use the library elsewhere
So the Android and iOS and Web react-based application for the same "project" will always be three different codebases, but they might have quite a lot of shared javascript code in form of reused libraries.

Resources