React to React Native

Join my journey into exploring the world of React Native as a React JS developer. This post covers some basic quick start guide and free resources to quickly get started with Mobile Development using JavaScript, React and web technologies.

React to React Native
Photo by Safar Safarov / Unsplash

While I had been a ReactJS developer for a substantial period, last year I had an opportunity to work on a React Native project. Given my existing understanding of React, I quickly learned and got onboarded with building applications on React Native. This post goes into detail, documenting the learning process for quickly adapting to React Native, assuming prior knowledge of React JS.

To kickstart the journey, I found a concise and short YouTube crash-course that helped me quickly grasp the basics.

React Native Vs React

  1. Component Semantics: use a <View /> element where a wrapper element like <div /> , <main /> etc is used. Like any other wrapper elements in JSX, It is meant to hold and lay out other elements or components . <View /> component is imported from react-native package.
  2. Text: text cannot be inserted directly; wrap it inside a <Text /> component to maintain consistency across platforms.
  3. Native Equivalent: React Native converts components to native equivalents of the respective OS.(e.g., <TextInput /> to ExitText in Android and UITextField in iOS; ).
  4. JavaScript Code and Logic: Functions, state logic, and any JavaScript logic run on a JS thread hosted by the React Native app in the native app built. The JavaScript logic written as a part of React Native codebase is not compiled to native equivalents, but instead its running on JS thread that is hosted by React Native App in the native app that was built. So, all UI components convert to native equivalents and all the JavaScript logic works as a JavaScript thread and not a native languague thread.
  5. React Navigation: Crucial for handling navigation in React Native. Understand setting up different navigators, such as Stack Navigator, Tab Navigator, and Drawer Navigator.
  6. Handling Platform Differences: React Native allows you to build for both iOS and Android, but there are platform-specific differences. Learn to handle variations in components, styling, and functionality for both iOS and Android.
  7. Testing Frameworks: The humble tools which we use for React Web like Jest, Enzyme, React Testing Library (Native) can also be used for testing React Native components.
  8. Camera Features: Numerous plugins cater to camera functionality in React Native, and I stumbled upon Vision Camera, which stands out for its comprehensive support of essential camera features.

React Native Semantics and Rules

  1. <ScrollView /> is a scrollable <View /> component.
  2. Use <Button /> for native-styled buttons; <Pressable /> for custom buttons with style flexibility.
  3. In case of <Button /> component, since the styling on iOS and Android is different, the color prop behaves like color and background-color respectively.
  4. If we wish to make some element tappable, or in other words we wish to track the tap events, we will wrap those components inside <Pressable /> . Thus, we can make a custom button using a <Pressable /> instead of using a <Button /> because <Button /> does not support a style prop.
  5. There are other non-deprecated components like <TouchableOpacity /> , <TouchableHighlight />,etc  but using <Pressable /> will make our codebase future proof (as per official documentation).
  6. Use <Modal /> for Lightbox, Overlays or Modals
  7. <Image /> for adding images
  8. To add images, we should use the <Image /> component.
  9. The "status bar" is the zone, typically at the top of the screen, that displays the current time, Wi-Fi and cellular network information, battery level and/or other status icons. We can style the status bar to use a light or a dark mode, change visibility and even add transitions while it becomes visible or hidden using <Status Bar /> component.
  10. We can also add Animations, create Alerts, check if the application is in foreground or background using AppState and more.

React Native Styling

  1. Inspired by CSS: The styling languague is inspired from CSS, but we do not have all the values we have in CSS. For instance, we can manually set text color using color property.

  2. Inline Styling: It is possible to write inline styles like in a normal React JS App, but generally not ideal due to code repetition.

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

const MyComponent = () => {
  return (
    <View style={{ backgroundColor: 'blue', padding: 20 }}>
      <Text style={{ color: 'white', fontSize: 16 }}>Hello, React Native!</Text>
    </View>
  );
};

export default MyComponent;
  1. StyleSheet Object: Use the StyleSheet object for optimized styling.

import React from 'react';
import { View, StyleSheet, Platform, Text } from 'react-native';


// Use the StyleSheet.create method to define your styles:
const styles = StyleSheet.create({
  container: {
    paddingVertical: Platform.OS === 'ios' ? 20 : 10,
  },
  text: {
    fontSize: 16,
    color: isDarkMode ? 'white' : 'black',
  },
});


// Apply the styles to your React Native component. 
const MyComponent = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>Some Text here</Text>           
      {/* other components */}
    </View>
  );
};

export default MyComponent;

  1. Flexbox Way of Styling: Every <View /> uses display: flex by default and uses CSS Flexbox way of aligning inner items. Default value for flexDirection is column. By Default, <View /> element only takes as much space as its children components require unless we add properties like flex (Grow/Shrink), width, height , etc.

  2. Cascading Styles: Cascading nature of CSS does not work in React Native.The style properties won't cascade from parent to child components. For instance, added inside will not cascade CSS properties, that is inherit properties like text color from component's style prop.

  3. Other Methods: Alternatively, We can also use CSS Modules and styled Components

import styled from 'styled-components/native';

const StyledText = styled.Text`
  font-size: 16px;
  color: ${(props) => (props.isBlue ? 'blue' : 'black')};

React Native Events

  1. Event Handling: Certain events like on input elements have similar event handlers as web but different names. For instance, <TextInput /> uses onChangeText instead of onChange, <Button /> uses onPress instead of onClick, etc.
  2. Gestures Galore: Master touch gestures using the PanResponder for advanced user interactions.PanResponder reconciles several touches into a single gesture. It makes single-touch gestures resilient to extra touches, and can be used to recognize basic multi-touch gestures.

React Native Performance Optimisations

  1. Scroll View Vs FlatList: Using <ScrollView /> to render a long list of items can cause performance issues as it renders all items, whether visible or not. To address this, opt for <FlatList /> for dynamic lists with numerous items. Unlike <ScrollView />, <FlatList /> efficiently loads only the visible items, enhancing overall app performance.
  2. React Performance Tricks: Use `useMemo` or `React.memo` for optimized performance.
  3. Alternatives to Memo: Dan Abramov wrote this article a while back discussing two basic techniques for improving rendering performance in React before resorting to memoization. Any state changes will cause the entire App to re-render, hence Dan suggests moving state down in the component hierarchy or lift content up based on whether a piece of state affects only a specific subtree or is used in a higher component. These approaches improve data flow and may enhance performance, with the added note that such optimizations should complement, not replace, memoization techniques like memo or useMemo. The author emphasizes the simplicity and underappreciated nature of these techniques, highlighting their potential benefits for future performance optimizations, such as with Server Components.
  4. Component Lifecycle: Understand the React Native component lifecycle for strategic optimizations.
  5. AsyncStorage: Leverage for efficient asynchronous data storage.
  6. Redux Integration: Explore Redux for state management in complex applications.

As we wrap up this comprehensive exploration into React Native, it's evident that the journey from ReactJS to React Native is not merely a transition but an evolution. From mastering the essential components like <View> and <Text> to unraveling the intricacies of touch gestures with PanResponder, the more we write the code, more we embark newer nuances of this technology.

The incorporation of the StyleSheet object for styling and strategic performance optimizations with techniques like useMemo underscores the finesse required in this mobile landscape. The expert advice from luminaries like Dan Abramov serves as a guiding light, emphasizing foundational techniques that complement the ever-expanding realm of memoization strategies. Feel free to share your thoughts on Twitter and stay tuned for more of such content!