React Native - Building Mobile Apps with JavaScript

4.7 (3 reviews total)
By Vladimir Novick
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Understanding Why React Native is the Future of Mobile Apps

About this book

The emergence of React Native has made creating mobile apps in JavaScript easier for developers. This book introduces you to the React Native framework and the mobile apps development process. It starts with how React Native fits into the world of hybrid apps, and why it’s a popular framework. You’ll learn how React Native works under the hood--compiling JavaScript to Native code to bridge JavaScript and native apps. Also, you’ll learn how to write React Native components and use the ReactJS way of structuring your app. Understand how to use the industry standard Redux architecture as well as MobX--a newly emerging approach for state management--making your apps more robust and scalable.

The mobile native world can be intimidating, with lots of platform-specific APIs. In this book, you’ll learn about the most important APIs with help of the real-world examples. You’ll also learn about the community packages that can help speed up your development. The book explains how to use these packages with JavaScript code, include native modules in your application, and write the modules yourself. Throughout the book, you will see examples of WhatsApp, Instagram, and YouTube apps and learn how to recreate them. You’ll also learn debugging and testing techniques, authentication, dealing with real data, and much more.

At the end we will walk through design to production process of Twitter app clone and will explain application release process to App Store and Play Store

Publication date:
August 2017
Publisher
Packt
Pages
434
ISBN
9781787282537

 

Chapter 1. Understanding Why React Native is the Future of Mobile Apps

Welcome to the first chapter. In this chapter, you will get a basic understanding of what React Native actually is and what it brings out of the box. Then, we will dive deeper and get familiar with how it works under the hood. You will learn the differences between the Native and React Native apps and understand that React Native brings with it lots of advantages over conventional mobile development for iOS and Android.

In this chapter, you will learn the following topics:

  • What is React Native?
  • How the React Native bridge from JavaScript to Native world works?
  • What are benefits of React Native?
 

What is React Native?


React Native is a framework developed by Facebook for building Native mobile apps in JavaScript. It's based on ReactJS, a Facebook library for building user interfaces.

React introduced some amazing concepts to build UI, and these concepts can be applied not only to web browser, but also to mobile. They include better state management techniques, a unidirectional data flow in applications, component-based UI construction, and much more. If you have a React background, you should be familiar with these concepts, but if you don't, no worries. You will see how these concepts are used by following the book.

React Native currently supports iOS and Android and there are plans to expand to other platforms. The change that React Native brings with it is that even while an application is written in JavaScript, it's compiled to Native code, so its performance is much better than so-called hybrid apps. These apps are written in JavaScript, HTML, and CSS and are executed inWebView(a browser embedded inside an app). Besides, React Native brings web-like developer experience, live reloading of your application during development, and much more--things mobile developers only dreams about.

The history of React Native

In order to understand the motivation behind creating React Native, it's important to understand what lead to the creation of React Native and what was the motivation for it.

It all begun with ReactJS

Before looking at the history of React Native, let's take a look at the history of ReactJS. After all, React Native is based on ReactJs and uses its concepts and best practices. For years in web development, there was a mantra: Dom Manipulation is expensive. Basically, it means that presenting your data to the browser or rendering it is a costly operation. Document Object Model (DOM) was built in the 80s to deal with simple HTML documents.

React is focused around the concept of Virtual DOM. Let's understand why this concept is called virtual. DOM stands for Document Object Model and means actual browser API to access HTML nodes structured in a tree-like structure. Virtual DOM is a representation of this same structure, but inside JavaScript without accessing HTML nodes directly.

React has an internal state, and when this state is updated, it knows to update DOM with batched updates. Also, React uses a JSX-XML-like syntax, which lets developers represent their React components hierarchies somewhat similar to writing XML, but doing it inside JavaScript.

Since React uses Virtual DOM, it's decoupled from exact browser implementation. This gave an idea to some developers at Facebook internal Hackathon to write a framework based on a solid React foundation, but that will render a UI not inside a browser, but instead will compile it to Native modules--Objective-C for iOS, and Java for Android.

Hackathon, that grew bigger

Yes, you heard it right. Great things emerge when great minds start hacking. That was exactly the case inFacebook internal Hackathonin Summer 2013. After creating React Native, it was publicly reviewed in January 2015 at the ReactJS conference. In March 2015, It was officially released by Facebook to open source and since then it has been available on GitHub:

Almost two years passed, and React Native grew to be the most popular and best framework for developing mobile apps. It even surpassed iOS and Android development according to Google Trends. It's a collective effort of React Native core team and the community, so after finishing the book and becoming a React Native professional, I encourage you to support this collective effort and contribute to React Native development.

Check out the following Google trends comparison between React Native, Android development, and iOS development:

React Native today

Today, React Native is considered to be the best choice for developing mobile applications since it gives you lots of advantages over traditional mobile development. It's not only a framework for external use. Facebook uses it for its Facebook groups, which is a combination of Native modules and React Native and for Facebook Ads Manager, which is built entirely using React Native.

The motivation of creating React Native

Apart from being a really cool Hackathon project, React Native had some solid foundation on why it was created in the first place. There were several things in mobile development that became a real bottleneck for companies creating mobile apps. Also, there were some things that the team behind React Native wanted to improve in mobile development workflow in general. Let's briefly look at them.

Mobile development is too specific

Let's talk about mobile development in general. iOS and Android are the two most popular platforms. Each platform uses a different programming language, has different APIs to deal with a device, and usually requires a different approach from the developer.

To summarize this, mobile development is coupled to a specific platform. If a company wants to create an Android application, it would need to hire an Android developer. If it needs to develop an iOS application, it will hire an iOS developer. These developers are not interchangeable. Application code, even when doing the same, can't be shared across platforms and basically needs to be written twice--once in Java, and once in Objective-C or Swift.

Taking the React approach

React introduced new concepts to web development, one of which is unidirectional data flow.

The meaning of unidirectional data flow this means can be expressed in the following formula:

It means that our UI is a function of an application state. That means that, instead of updating the UI directly in an imperative way, we change the state and the UI is updated accordingly by the internal React mechanism.

Let's check the following use case: A user clicks on a button, and it's color is updated. Usually, we attach some kind of event listener to the button click, and when it's performed, we update the button color directly. In React, instead of changing the button color directly, we change the component state and React propagates this change to the UI.

Another concept is splitting your UI to reusable components. Since you focus on each component in separation, it's easier to test and to reuse it across the app, meaning more Don't Repeat Yourself (DRY) code and less bugs.

The declarative nature of ReactJS components and their tree-like structure provide powerful feedback on how your application is laid out. This speeds up development, because code is easier to read and maintain.

The previously mentioned concepts were used for web development, but there were no reason not to reuse them for mobile development. So, these concepts were incorporated in React Native and used upto now. We will cover how this works in detail in later chapters.

Making developer experience state of the art

One of the important concepts in software development in general is a great developer experience. If your application is not working, you need to debug it. Also, when developing for mobile, each minor change means that you need to wait for your code to compile, restart your app, and watch whether it has changed. React Native was created with an idea of overcoming this short-coming to give the best developer experience, and it succeeded in lots of ways.

Since React Native is based on web development concepts, it allowed developers to use one of the most popular web development tools, Chrome Developer Tools. When you run React Native in the development mode, you can attach your application to Chrome browser and use its developer tools. You can debug your code, check network requests, profile memory usage, and do all the things you can do in Chrome DevTools when developing for the web.

Another new concept that has been introduced into web development and, with React Native was also got into mobile development, is a concept of Hot Module Reloading or HMR. HMR is a technique used by the JavaScript bundling system to "know" which modules were changed and reload them without doing a full page reload.

Introducing this together with live reload to the React Native ecosystem provides instant feedback during development and shortens development cycles.

In terms of layouting your application, layout engines for iOS and Android Native apps are different. React Native unites it under one way to layout your application using a modern web technique called flexbox. Also, you will see when we will get into the code that styles look very similar to inline styles used in web development.

How React Native is different from hybrid applications?

Was React Native the first framework used to build mobile applications in JavaScript? Of course not. For quite a while, there was the Cordova platform. On top of it, there were popular frameworks such as Ionic or Sencha Touch. Cordova created a new kind of application: hybrid apps.

What are hybrid applications?

Cordova gave a developer the ability to make calls to Native mobile APIs while writing their application using JavaScript, HTML, and CSS. The reason these types of apps are called hybrid is because they don't really create Native experiences. The resulting app runs inside a WebView as mentioned earlier and may look almost the same as a Native one, but there will always be small things that will matter, for example, scrolling, accessing keyboard, animations, and much more. There were lots of hybrid apps written and published to Play and App Stores, but none of them feel really Native.

So, you may ask, if they are all bad, then why were they created in the first place? There are several reasons:

  • Code reuse across multiple platforms
  • Development speed
  • Web technologies used no platform-specific mobile developers

One of the main drivers of creating hybrid apps was code reuse. Write your code once in JavaScript, HTML, and CSS, and you are good to go. The application will work both on Android and iOS. Of course, it's undoubtedly faster to develop a single application for multiple platforms. For companies, hiring mobile developers for every platform was more costly than retraining web developers to develop for mobile.

Why Native applications lead the way?

When Cordova came out and hybrid apps started to emerge, it all looked very promising, but very fast hybrid apps showed their bad side.

They introduced new architectural complexities and more technologies to use in the project. While the motivation was to let developers create mobile experiences using web technologies, it was not as simple as that and always included involvement in Native technologies; thus, the overall experience was not the same.

Since hybrid applications are running inside a WebView, the level of interaction and performance is very limited. Animations can become laggy and do not compare to the Native approach.

Is React Native really a Native framework?

So how is React Native different? Well, it doesn't fall under the hybrid category because the approach is different. While hybrid apps are trying to make platform-specific features reusable between platforms, React Native has platform-independent features, but also has lots of specific platform implementations. Meaning that on iOS and on Android, code will look different, but somewhere between 70-90 percent of code will be reused.

Also, React Native does not depend on HTML or CSS. You write in JavaScript, but this JavaScript is compiled to platform-specific Native code using the React Native bridge. It happens all the time, but it's optimized in a way that the application will run smoothly in 60 fps.

So, to summarize, React Native is not really a Native framework, but it's much closer to Native code than hybrid apps. Now, let's dive a bit deeper and understand how JavaScript gets converted into Native code.

 

How the React Native bridge from JavaScript to Native world works?


Let's dive a bit deeper and understand how React Native works under the hood, which will help us understand how JavaScript is compiled to a Native code and how the whole process works. It's crucial to know how the whole process works, so if you have performance issues some day, you will understand where it originates.

Information flow

So we've talked about React concepts that power up React Native, and one of them is that UI is a function of data. You change the state, and React knows what to update. Let's visualize now how information flows through the common React app. Check out the following diagram:

  • We have a React component, which passes data to three child components
  • What is happening under the hood is that a Virtual DOM tree is created, representing these component hierarchies
  • When the state of the parent component is updated, React knows how to pass information to the children
  • Since children are basically a representation of UI, React figures out how to batch Browser DOM updates and executes them

So now let's remove Browser DOM and think that instead of batching Browser DOM updates, React Native does the same with calls to Native modules.

So what about passing information down to Native modules? It can be done in two ways:

  • Shared mutable data
  • Serializable messages exchanged between JavaScript and Native modules

React Native takes the second approach. Instead of mutating data on shareable objects, it passes asynchronous serialized batched messages to the React Native Bridge. The Bridge is the layer that is responsible for gluing together Native and JavaScript environments.

Architecture

Let's take a look at the following diagram, which explains how React Native architecture is structured and take a walk through the diagram:

In the preceding diagram, three layers are mentioned:Native, Bridge, and JavaScript. The Native layer is pictured last in the picture because it's the layer that is closest to the device itself. The Bridge is the layer that connects JavaScript and Native modules and is basically a transport layer that transports asynchronous serialized batched response messages from JavaScript to Native modules.

When an event is executed on the Native layer--it can be a touch, timer, or network request--basically, any event involving device Native modules. Its data is collected and is sent to the Bridge as a serialized message. The Bridge passes this message to the JavaScript layer.

The JavaScript layer is an event loop. Once the Bridge passes Serialized payload to JavaScript, Event is processed and your application logic comes into play.

If you update the state, triggering your UI to rerender, for example, React Native will batch Update UI and send it to the Bridge. Bridge will pass this Serialized batched response to the Native layer, which will process all commands that it can distinguish from a serialized batched response and will Update UI accordingly.

Threading model

Up till now, we've seen that there is lots of stuff going on under the hood of React Native. It's important to know that everything is done on three main threads:

  • UI (the application's main thread)
  • Native modules
  • JavaScript runtime

The UI thread is the main Native thread where native-level rendering occurs. It is here, where your platform of choice, iOS or Android, does measuring, layouting, and drawing.

If your application accesses any Native APIs, it's done on a separate Native modules thread. For example, if you want to access the camera, geo location, photos, and any other Native API, planning and gestures in general are also done on this thread.

The JavaScript runtime thread is the thread where all your JavaScript application code will run. It's slower than the UI thread since it's based on a JavaScript event loop, so if you do complex calculations in your application that leads to a lot of UI changes, these can lead to bad performance. The rule of thumb is that if your UI changes slower than 16.67 ms, then your UI will appear sluggish.

 

The benefits of React Native


React Native brings with it many advantages for mobile development. We've covered some of them briefly before, but let's go over them now in more detail. These advantages are what has made React Native so popular and why it is trending now. Also, most of all, it helped web developers to start developing Native apps with a relatively short learning curve compared to overhead learning for Objective-C and Java.

Developer experience

One of the amazing changes React Native brings to the mobile development world is enhancement of the developer experience. If we check the developer experience from the point of view of web developer, it's awesome. For a mobile developer, it's something that every mobile developer has dreamt of. Let's go over some of the features React Native brings for us out of the box.

Chrome DevTools debugging

Every web developer is familiar with Chrome Developer tools. These tools give us an amazing experience when debugging web applications. In mobile development, debugging mobile applications can be hard. Also, it's really dependent on your target platform. None of mobile application debugging techniques even come near the web development experience.

In React Native, we already know that a JavaScript event loop is running on a separate thread, and it can be connected to Chrome DevTools. By clicking on Ctrl/Cmd+D in an application simulator (we will cover all the steps of setting such a simulator in future chapters), we can attach our JavaScript code to Chrome DevTools and bring web debugging to a mobile world. Let's take a look at the following screenshot:

Here, you see a React Native debug tools. By clicking onDebug JS Remotely, a separate Google Chrome window is opened, where you can debug your applications by setting breakpoints, profiling CPU and memory usage, and much more.

The Elements tab in Chrome Developer tools won't be relevant, though. For that, we have a different option. Let's take a look at what we will get with Chrome Developer tools Remote debugger.

Currently, Chrome Developer Tools are focused on the Sources tab. You can note that JavaScript is written in ECMAScript 2015 syntax. For those of you who are not familiar with React JSX, you see a weird XML-like syntax. Don't worry, this syntax will also be covered in the book in the context of React Native.

If you put debugger inside your JavaScript code, or a breakpoint in your Chrome development tools, the app will pause on this breakpoint or debugger, and you will be able to debug your application while it's running.

Live reload

As you can see in the React Native debugging menu, the third row says Live Reload. If you enable this option, whenever you change your code and save, the application will be automatically reloaded.

This ability to live reload is something mobile developers only dream of. There is no need to recompile an application after each minor code change. Just save, and the application will reload itself in the simulator. This greatly speeds up application development and makes it much more fun and easy than conventional mobile development. The workflow for every platform is different, whereas the experience is the same in React Native--the platform for which you develop does not matter.

Hot reload

Sometimes, you develop a part of the application that requires several user interactions to get to. Consider, for example, logging in, opening the menu, and choosing an option. When we change our code and save, while live reload is enabled, our application is reloaded and we need to do these steps once again.

However, it does not have to be like that. React Native gives us an amazing experience of hot reloading. If you enable this option in React Native development tools and if you change your React Native component, only the component will be reloaded while you stay on the same screen you were on before. This speeds up the development process even more.

Component hierarchy inspections

I've said before that we cannot use the elements panel in Chrome development tools, but how do you inspect your component structure in React Native apps? React Native gives us a built-in option in development tools called Show Inspector. When you click on it, you will get the following window:

After the Inspector is opened, you can select any component on the screen and inspect it. You will get the full hierarchy of your components as well as their styling:

In this example, I've selected the Welcome to React Native! text. In the opened pane, I can see its dimensions, padding margin, and component hierarchy.As you can see, it's IntroApp/Text/RCTText.

RCTText is not a React Native JavaScript component, but a Native Text component, connected to React Native bridge. In that way, you also can see that this component is connected to a Native text component.

There are even more dev tools available in React Native that I will cover later on, but we can all agree that the development experience of React Native is outstanding.

Web-inspired layout techniques

Styling for Native mobile apps can be really painful sometimes. Also, it's really different between iOS and Android. React Native brings another solution. As you may have seen before, the whole concept of React Native is about bringing the web development experience to mobile app development.

That's also the case for creating layouts. The modern way of creating a layout for the web is using flexbox. React Native decided to adopt this modern technique for the web and bring it to the mobile world with a few differences.

In addition to layouting, all styling in React Native is very similar to using inline styles in HTML.

Let's take a look at an example:

const styles = StyleSheet.create({
container: {
  flex: 1,
  justifyContent: 'center',
  alignItems: 'center',
  backgroundColor: '#F5FCFF',
});

As you can see in this example, there are several properties of flexbox used as well as a background color. This really reminds us of CSS properties; however, instead of using background-color, justify-content, and align-items, CSS properties are named in a camel case manner in order to apply these styles to the Text component, for example. It's enough to pass them as follows:

<Text styles={styles.container}>Welcome to React Native </Text>

Styling will be discussed in the next chapters; however, as you can see from the preceding example, styling techniques are similar to web techniques. They are not dependent on any platform and are the same for both iOS and Android.

Code reusability across applications

In terms of code reuse, if an application is properly architectured (something that you will also learn in this book), around 80% to 90% of code can be reused between iOS and Android. This means that in terms of development speed, React Native beats mobile development.

Sometimes, even code used for the web can be reused in a React Native environment with small changes. This really brings React Native to the top of the list of the best frameworks to develop Native mobile apps.

 

Summary


So, we've discussed several things about React Native. We started by learning the motivation for creating React Native, that is, its history. Then, we dived deeper into how it works under the hood.

The whole explanation of React Native architecture and threads may sound intimidating, but I personally think it's important to understand how things work under the hood before starting to get into understanding bytes and bits of framework. To distinguish parallels between web and mobile and to explain the whole React Native bridge architecture in one sentence, I think the best way will be to say that React Native communication between JavaScript Runtime and Native modules is somewhat similar to client-server interaction: both send serialized data over some kind of transport. Finally, the chapter ends by covering some of the advantages of the React Native framework.

More and more companies have started to adopt React Native for their production apps. Facebook itself uses React Native for some of their applications, and the overall growth of React Native usage has lately become exponential.

It's important to understand that React Native bridges the gap between the Native mobile development and web development and removed lots of obstacles for web developers to enter the mobile development world. I hope that you believe that the future of mobile development is in learning React Native, and the fact that you are reading this means that you are ready to take this train to the future. Enjoy your ride!

What's next? I strongly believe that real knowledge comes from hands-on experience. So, in the next chapter, the first thing we will do is to set up a development environment so that you will be able to run your first React Native application. Then, you will get familiar with important concepts of React and React Native, and it will get you prepared for creating your first React Native applications.

About the Author

  • Vladimir Novick

    Vladimir Novick is developer, software architect, public speaker, and consultant. Coming from a web programming background, he started programming for mobile using React Native around 2015. Vladimir works in the web, mobile, VR, AR, and Internet of Things fields daily, developing complex enterprise-level software, consulting clients, contributing to open source, and teaching, and talking at various meetups and conferences. He is also the author of several courses and workshops.

    Previously, Vladimir worked in the video, gaming, sports, and entertainment industries where he architected and developed large-scale web applications for hundreds of millions of users, each month.

    Browse publications by this author

Latest Reviews

(3 reviews total)
I enjoy reading the book...
It got interesting for me starting with chapter 7.
GREAT CONTENT! EXACTLY WHAT I NEEDED

Recommended For You

Book Title
Access this book, plus 7,500 other titles for FREE
Access now