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

Fundamentals of React Native

Fundamentals of React Native

Mustafa Berkay Mutlu

May 31, 2017
Tweet

More Decks by Mustafa Berkay Mutlu

Other Decks in Programming

Transcript

  1. What is React Native React is a framework created by

    Facebook for data driven web interfaces. The key point with React Native is that it aims to primarily bring the power of the React programming model to mobile app development. React Native is like React, but it uses native components instead of web components as building blocks. • Started as Facebook’s internal hackathon project, in the summer of 2013 • The first public preview was in January of 2015 at React.js Con. • Supportted minimum SDK versions: Android 4.1 (API 16) and iOS 8.0
  2. Who's using React Native • Facebook (iOS & Android) •

    Facebook Ads Manager (iOS & Android) • F8 (iOS & Android) • Instagram (iOS & Android) • AirBnb (iOS & Android) • Walmart (iOS & Android) • Tesla (iOS & Android) • Baidu Mobile (iOS & Android) • Bloomberg (iOS & Android) • Vogue (iOS) • li.st (Android) • Discord (iOS) • Gyroscope (iOS) • Delivery.com (iOS & Android) • Flare by GoDaddy (iOS & Android) • SoundCloud Pulse (iOS)
  3. What You’ll Need to Start Android • Node • Python2

    • Java 8 • Android Studio • Android Emulator iOS • Node • Watchman • Xcode • iOS Simulator
  4. IDE The recommended IDE is Atom, with a plugin on

    top of it, Nuclide, which adds support for React Native development and for its recommended static analysis tool Flow. Also: Windows is not supported.
  5. Debugging The Nuclide Debugger provides many capabilities allowing you to

    have a productive debug loop, including inspection, watches, setting breakpoints, step in/over/out, etc. • Build upon Chrome Developer Tools • (For me) far behind the native development IDEs
  6. Hot Reloading Hot Reloading is similar in concept to Instant

    Run on Android. Every time a source file was saved, the changes were deployed immediately on the device where the app was running, thus greatly expediting the feedback loop.
  7. Native Coding There are certain features that cannot be implemented

    solely in JavaScript, native code is needed for: • push notifications • deep linking • native UI components that need to be exposed to React Overall approximately 80% of the code is shared between iOS and Android and written in JavaScript.
  8. Misconceptions No. The JavaScript communicates with native components (Java on

    Android, Objective C on iOS). The communication occurs through the so-called "bridge". If at any time you feel that this communication slows things down too much, you can choose to implement the Javascript functionality in Java or Objective C in order to run purely native. In this case, you are writing directly in native code, so there's no Javascript to native compilation. Does the JS code compiled to native code?
  9. Misconceptions Just use’em! You don’t have to wait for someone

    to write a React Native wrapper around platform API’s. What if I want to use the platform’s latest API’s?
  10. React & React Native React import React from 'react'; class

    HelloWorld extends React.Component { render() { return ( <div> <span> Hello World </span> </div> ); } } React Native import React from 'react'; import { View, Text } from 'react-native'; class HelloWorld extends React.Component { render() { return ( <View> <Text> Hello World </Text> </View> ); } }
  11. Styles const styles = StyleSheet.create({ container: { flex: 1, justifyContent:

    'center', alignItems: 'center', }, message: { fontSize: 28, fontColor: '#222222', }, }); import React from 'react'; import { View, Text, StyleSheet } from 'react-native'; class HelloWorld extends React.Component { render() { return ( <View style = { styles.container } > <Text style = { styles.message } > Hello World </Text> </View> ); } }
  12. Props Properties (or Props for short) used for passing data

    to components. • Immutable • To use it, refer the this.props inside the render function. class Greeting extends Component { render() { return ( <Text>Hello { this.props.name }! </Text> ); } } export default class LotsOfGreetings extends Component { render() { return ( <View style={{alignItems: 'center'}}> <Greeting name='Rexxar' /> <Greeting name='Jaina' /> </View> ); } }
  13. • Initialize in component constructor • Update it using setState

    • You can access previous state inside the setState function • Unlike Props, State is mutable • Each of the prop and state change triggers a complete re-render of the component State export default class MyContainerComponent extends Component { constructor() { super() this.state = { myText: 'Lorem ipsum dolor sit amet.' } } render() { return ( <View> <Text> { this.state.myText } </Text> </View> ); } }
  14. Native Modules Sometimes an app needs access to a platform

    API that React Native doesn't have a corresponding module for yet. Maybe you want to reuse some existing Java code without having to reimplement it in JavaScript. It is possible to write real native code and have access to the full power of the platform.
  15. Native Modules 1. Write a Java class that extends ReactContextBaseJavaModule

    2. Override getName() method to return unique name 3. (Optional) override getConstants() 4. Add your native methods and annotate them with @ReactMethod 5. Register your module inside your ReactPackage class 6. Access your native method from JS using the name you defined in getName()
  16. Native Modules public class ToastModule extends ReactContextBaseJavaModule { private static

    final String DURATION_SHORT_KEY = "SHORT"; private static final String DURATION_LONG_KEY = "LONG"; public ToastModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "ToastAndroid"; } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT); constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG); return constants; } @ReactMethod public void show(String message, int duration) { Toast.makeText(getReactApplicationContext(), message, duration).show(); } }
  17. Native Modules 'use strict'; /** * This exposes the native

    ToastAndroid module as a JS module. This has a * function 'show' which takes the following parameters: * * 1. String message: A string with the text to toast * 2. int duration: The duration of the toast. May be ToastAndroid.SHORT or * ToastAndroid.LONG */ import { NativeModules } from 'react-native'; module.exports = NativeModules.ToastAndroid; import ToastAndroid from './ToastAndroid'; ToastAndroid.show('Awesome', ToastAndroid.SHORT);
  18. Native Modules @ReactMethod public void measureLayout( int tag, int ancestorTag,

    Callback errorCallback, Callback successCallback) { try { measureLayout(tag, ancestorTag, mMeasureBuffer); float relativeX = PixelUtil.toDIPFromPixel(mMeasureBuffer[0]); float relativeY = PixelUtil.toDIPFromPixel(mMeasureBuffer[1]); float width = PixelUtil.toDIPFromPixel(mMeasureBuffer[2]); float height = PixelUtil.toDIPFromPixel(mMeasureBuffer[3]); successCallback.invoke(relativeX, relativeY, width, height); } catch (IllegalViewOperationException e) { errorCallback.invoke(e.getMessage()); } } UIManager.measureLayout( 100, 100, (msg) => { console.log(msg); }, (x, y, width, height) => { console.log(x + ':' + y + ':' + width + ':' + height); } );
  19. React Navigation React Navigation is a navigation library that can

    deliver 60 fps animations and utilize native components to deliver a great look and feel. React Native Stack
  20. React-Navigation (contd.) BasicApp.js const BasicApp = StackNavigator({ Main: {screen: MainScreen},

    Profile: {screen: ProfileScreen}, }); MainScreen.js class MainScreen extends React.Component { static navigationOptions = { title: 'Welcome', }; render() { const { navigate } = this.props.navigation; return ( <Button title="Go to Jane's profile" onPress={() => navigate('Profile', { name: 'Jane' })} /> ); } } ProfileScreen.js class ProfileScreen extends React.Component { static navigationOptions = ({navigation}) => ({ title: navigation.state.params.name, }); render() { const { goBack } = this.props.navigation; return ( <Button title="Go back" onPress={() => goBack()} /> ); } }
  21. React Native Stack Redux Redux is a predictable state container

    for JavaScript apps. It lets us manage the application state by using an immutable datastore. • Might be overkill for simple apps
  22. React Native Stack CodePush CodePush lets you push code to

    your device and release an update without the work of putting the app on stores. Allowing your app to update without deploying to the app store, Code Push allows you to change the UI/UX, business logic fix bugs, load hot-fixes. • Cannot push any code touching the native side of React Native • Rollback support • Supported by iOS 8+ and Android 4.1+
  23. React Native Stack Flow Flow is a static type checker

    for your JavaScript code. It does a lot of work to make you more productive. Making you code faster, smarter, more confidently, and to a bigger scale. Flow checks your code for errors through static type annotations. • Open Source and maintained by Facebook
  24. Pros Code Reuse The list below shows the percentage of

    code shared between the apps for some of the Instagram products, which could be used as a proxy to measure how we managed to improve developer velocity: • Post Promote: 99% • SMS Captcha Checkpoint: 97% • Comment Moderation: 85% • Lead Gen Ads: 87% • Push Notification Settings: 92%
  25. Pros Deployment One of the main advantages of React Native

    is the ability to push quick bug fixes over-the-air, bypassing app stores, which means the React Native JavaScript bundle will be hosted on a server and retrieved by the client directly, similar to how the web works. Tools like Microsoft CodePush can be used to map bundles to the correct app versions. But supporting multiple versions of the app at the same time is an overhead that should be considered when deciding to use React Native.
  26. Pros Active Development of React Native React Native is developed

    and maintained by Facebook. It has 2 weeks of release cycle and under heavy development. The open source community is fantastic about developing and releasing new features and performance tweaks. But upgrading your React Native version tends to be a massive pain, especially if you have a platform built around React Native.
  27. Cons Differences between iOS and Android There are enough inconsistencies

    between the functionality of React Native on iOS and on Android to make it tricky to support both platforms. For example, the style property “overflow” is supported on iOS but not Android. In the React Native documentation you can see many properties and features marked as “Android only” or “iOS only”.
  28. Cons Development and debugging React Native code behaves differently in

    debug mode vs regular mode due to the fact that React Native utilizes a different JavaScript engine for each of these two modes. When a bug is particular to regular mode, it can naturally be hard to debug because it’s irreproducible in debug mode.
  29. Cons Nuclide React Native’s offical IDE Nuclide can be considered

    fallen behind when we think the features the native IDEs offering.
  30. Cons Uncertain Roadmap and Tight Coupling An app built upon

    the React Native is very dependent to the platform. If Facebook stops maintaining React Native, your app’s development will stop and you will be considering a React Native replacement for your app. Facebook hasn’t made any long-term commitments to maintaining React Native for a sustained period of time.
  31. Cons Dependencies React Native has a total of 648 dependencies.

    Your app is built on more than 600 people’s sustained efforts. This is also a pitfall: you depend on 648 volunteers to keep maintaining their library for the lifetime of your app, without any formal commitment. Will their licenses stay compatible with your software? Hopefully.
  32. What Others Said About React Native “We found that a

    good use case for React Native can be found in applications that need short time support, for example an app for a one-shot event like a concert or a conference. However after our month-long investigation we can definitively say that React Native is not a mature or stable platform yet. For this reason, we think that React Native is not ready to be used in a long-lasting supported application. React Native seems to be suitable for apps with simple UI, simple animations, and not long life or performance-critical apps.” - Novoda Blog, July 5th 2016
  33. What Others Said About React Native “React Native enables quick

    prototyping and a very high initial velocity. Basic features are relatively easy to implement. If needed, they can be extended with native code and native views, and also integrate well with other view controllers. But with all the pros, there are some cons, too. It’s natural that JavaScript code is not as efficient for calculation-intensive tasks, and there is an overhead when JavaScript is controlling native elements. JavaScript has a single dedicated device thread, while native code is free to use whatever threads it wants. In performance, React Native stays behind an optimized native application.” - DevBridge Group, April 28th 2016
  34. References • A brief history of React Native • React

    Native Docs • Why I'm not a React Native Developer • React Native at Airbnb • React Native at Instagram • React Native: Is it the end of native development? • React-Native Stack 2017